Computers Windows Internet

Php foreach command. About the intricacies of foreach in PHP. Unpacking nested arrays with list ()

The For Each ... Next loop in VBA Excel, its syntax and description of individual components. Examples of using the For Each ... Next loop.

The For Each ... Next loop in VBA Excel is designed to execute a block of statements with respect to each element from a group of elements (range, array, collection). This wonderful loop is used when the number of elements in a group and their indexing are unknown, otherwise, it is preferable to use it.

For Each ... Next Loop Syntax

For Each element In group [statements] [Exit For] [statements] Next [element]

V square brackets the optional attributes of the For Each ... Next loop are specified.

For Each ... Next Loop Components

*If a For Each ... Next loop is used in VBA Excel to loop through the elements of a collection (Collection object) or array, then the variable element must be declared with data type Variant otherwise the loop will not work.

**If you do not use your code in the loop, the meaning of using the loop is lost.

For Each ... Next Loop Examples

Loop for a range of cells

On the active sheet of an Excel workbook, select a range of cells and run the following procedure:

Sub test1 () Dim element As Range, a As String a = "Data retrieved from the For Each ... Next:" For Each element In Selection a = a & vbNewLine & "Cell" & element.Address & _ " contains the value: "& CStr (element.Value) Next MsgBox a End Sub

The MsgBox information window will display the addresses of the selected cells and their contents, if any. If a lot of cells are selected, then the complete information on all cells will not be displayed, since the maximum length of the parameter Prompt is approximately 1024 characters.

Loop for sheet collection

Copy the following VBA procedure into Excel workbooks:

Sub test2 () Dim element As Worksheet, a As String a = "List of worksheets contained in this book:" For Each element In Worksheets a = a & vbNewLine & element.Index _ & ")" & element.Name Next MsgBox a End Sub

The MsgBox information window will display a list of the names of all sheets of the Excel workbook by the ordinal number of their tabs corresponding to their indices.

Loop for an array

Assign a list of animal names to the array and in the For Each ... Next loop write them to a variable a... Information window MsgBox will display a list of animal names from a variable a.

Sub test3 () Dim element As Variant, a As String, group As Variant group = Array ("hippopotamus", "elephant", "kangaroo", "tiger", "mouse") " sheet, for example the selected one: group = Selection a = "The array contains the following values:" & vbNewLine For Each element In group a = a & vbNewLine & element Next MsgBox a End Sub

Let's repeat the same VBA procedure, but set all the array elements in the For Each ... Next loop to Parrot. The MsgBox information window will display a list of animal names, consisting only of parrots, which proves the possibility of editing the values ​​of the array elements in the For Each ... Next loop.

Sub test4 () Dim element As Variant, a As String, group As Variant group = Array ("hippopotamus", "elephant", "kangaroo", "tiger", "mouse") " sheet, for example, the selected one: group = Selection a = "The array contains the following values:" & vbNewLine For Each element In group element = "Parrot" a = a & vbNewLine & element Next MsgBox a End Sub

This code, like everything else in this article, was tested in Excel 2016.

Loop for collection of subdirectories and exit the loop

In this example, we will add to the variable a names of subdirectories on disk C your computer. When the cycle reaches the folder Program Files, it will add to the variable a its name and message: “Enough, I will not read further! Regards, your For Each ... Next loop. "

Sub test5 () Dim FSO As Object, myFolders As Object, myFolder As Object, a As String "Create a new FileSystemObject and assign it to the" FSO "variable Set FSO = CreateObject (" Scripting.FileSystemObject ")" Extract the list of subdirectories on disk "C "and assign" it to the variable "myFolders" Set myFolders = FSO.GetFolder ("C: \") a = "Folders on disk C:" & vbNewLine "Loop through the list of subdirectories and add their names to the variable" a "" after reaching the "Program Files" folder, exit the loop For Each myFolder In myFolders.SubFolders a = a & vbNewLine & myFolder.Name If myFolder.Name = "Program Files" Then a = a & vbNewLine & vbNewLine & "Enough, read on I won't! "_ & vbNewLine & vbNewLine &" Regards, "& vbNewLine & _" Your For Each ... Next loop. "Exit For End If Next Set FSO = Nothing MsgBox a End Sub

Information window MsgBox will display a list of the names of subdirectories on the disk C your computer to the folder Program Files inclusive and the message of the cycle about the termination of its work.

As a result of the program's work, not only the names of the subdirectories visible when you navigate to the disk in the explorer will be displayed C but also hidden and service folders... To view a list of all subdirectories on disk C, comment out the code section from If before End If inclusive and run the procedure in the VBA Excel editor.

Do while and foreach loops

The do loop. ... ... while

The do ... while loop in C #, it is a post-condition version of while. This means that the loop condition is checked after the loop body is executed. Therefore, do ... while loops are useful in situations where a block of statements must be executed at least once. The following is the general form of the do-while loop statement:

do (statements;) while (condition);

If there is only one operator, curly braces are optional in this notation. However, they are often used to make the do-while construct more readable and not to be confused with the while loop construct. The do-while loop runs as long as the conditional expression is true. An example of using the do-while loop is the following program that calculates the factorial of a number:

Using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 (class Program (static void Main (string args) (try (// Calculate the factorial of int i, result = 1, num = 1; Console.WriteLine ("Enter a number:"); i = int.Parse (Console .ReadLine ()); Console.Write ("\ n \ nFactorial (0) =", i); do (result * = num; num ++;) while (num

Foreach loop

Foreach loop serves for cyclic access to the elements of a collection, which is a group of objects. C # defines several kinds of collections, each of which is an array. The following is the general form of the foreach loop statement:

foreach (type loop_variable_name in collection) operator;

Here type cycle_variable_name denotes the type and name of a loop control variable that gets the value of the next item in the collection at each step of the foreach loop. And a collection denotes a cyclically polled collection, which hereinafter is an array. Therefore, the type of the loop variable must match the type of the array element. In addition, the type can be denoted keyword var. In this case, the compiler determines the type of the loop variable based on the type of the array element. This can be useful for dealing with certain kinds of queries. But, as a rule, the type is specified explicitly.

The foreach loop statement works as follows. When the loop starts, the first element of the array is selected and assigned to the loop variable. At each subsequent step of the iteration, the next element of the array is selected and stored in the loop variable. The loop ends when all elements of the array are selected.

The foreach loop lets you loop through each item in the collection (an object representing a list of other objects). Formally, in order for something to be considered a collection, it must support the IEnumerable interface. Examples of collections include C # arrays, collection classes from the System.Collection namespace, and custom collection classes.

(PHP 4, PHP 5, PHP 7)

Design foreach provides an easy way to iterate over arrays. Foreach works only with arrays and objects, and will generate an error when trying to use it with variables of other types or uninitialized variables. There are two types of syntax:

foreach (array_expression as $ value) statement foreach (array_expression as $ key => $ value) statement

The first loop iterates over the array specified with array_expression... At each iteration, the value of the current element is assigned to a variable $ value and the internal pointer of the array is increased by one (thus, at the next iteration of the loop, work will occur with the next element).

The second loop will additionally correlate the key of the current element with a variable $ key at each iteration.

Comment:

When the operator foreach starts execution, the internal pointer of the array is automatically set to its first element This means that there is no need to call the function reset () before using the loop foreach.

Since the operator foreach relies on an internal array pointer, changing it inside the loop can lead to unpredictable behavior.

In order to directly change the elements of the array inside the loop, the variable $ value must be preceded by &. In this case, the value will be assigned by reference.

$ arr = array (1, 2, 3, 4);
foreach ($ arr as & $ value) (
$ value = $ value * 2;
}
// $ arr is now array (2, 4, 6, 8)
unset ($ value); // break the link to the last element
?>

Pointer to $ value possible only if the array being iterated over can be referenced (i.e., if it is a variable). The following code won't work:

foreach (array (1, 2, 3, 4) as & $ value) (
$ value = $ value * 2;
}
?>

Attention

Link $ value the last element of the array remains even after the operator foreach finished work. It is recommended to destroy it using the function unset ().

Comment:

Operator foreach does not support the ability to suppress error messages using the "@" prefix.

You may have noticed that the following constructs are functionally identical:


reset ($ arr);
while (list (, $ value) = each ($ arr)) (
echo "Value: $ value
\ n ";
}

foreach ($ arr as $ value) (
echo "Value: $ value
\ n ";
}
?>

The following constructs are also functionally identical:

$ arr = array ("one", "two", "three");
reset ($ arr);
while (list ($ key, $ value) = each ($ arr)) (

\ n ";
}

foreach ($ arr as $ key => $ value) (
echo "Key: $ key; Value: $ value
\ n ";
}
?>

Here are some more examples demonstrating the use of the operator:

/ * Example 1: value only * /

$ a = array (1, 2, 3, 17);

foreach ($ a as $ v) (
echo "Current value of \ $ a variable:$ v. \ n ";
}

/ * Example 2: value (for illustration, the array is output as a value with a key) * /

$ a = array (1, 2, 3, 17);

$ i = 0; / * for clarification only * /

Foreach ($ a as $ v) (
echo "\ $ a [$ i] => $ v. \ n";
$ i ++;
}

/ * Example 3: key and value * /

$ a = array (
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);

foreach ($ a as $ k => $ v) (
echo "\ $ a [$ k] => $ v. \ n";
}

/ * Example 4: multidimensional arrays * /
$ a = array ();
$ a [0] [0] = "a";
$ a [0] [1] = "b";
$ a [1] [0] = "y";
$ a [1] [1] = "z";

foreach ($ a as $ v1) (
foreach ($ v1 as $ v2) (
echo "$ v2 \ n";
}
}

/ * Example 5: dynamic arrays * /

Foreach (array (1, 2, 3, 4, 5) as $ v) (
echo "$ v \ n";
}
?>

Unpacking nested arrays with list ()

(PHP 5> = 5.5.0, PHP 7)

PHP 5.5 added the ability to traverse an array of arrays with unpacking the nested array into loop variables by passing list () as a value.

The foreach construct is a flavor of for included in the language to make it easier to iterate over the elements of an array. There are two flavors of the foreach command, targeting different types of arrays:

foreach (array as $ element) (

foreach (array as $ key => $ element) (

For example, when executing the following snippet:

$ menu = аrrау ("pasta", "steak", "potatoes", "fish", "fries");

foreach ($ menu as $ item) (

print "$ item
";

the following output will be displayed:

In this example, two things should be noted. First, the foreach construct automatically returns to the beginning of the array (this does not happen in other looping constructs). Second, there is no need to explicitly increment the counter or otherwise move to the next element in the array — this happens automatically with each iteration of foreach.

The second option is used when working with associative arrays:

$ wine_inventory = array (

"merlot" => 15,

"zinfandel" => 17,

"sauvignon" => 32

foreach ($ wine_inventory as $ i => $ item_count) (

print "$ item_count bottles of $ i remaining
";

In this case, the result looks like this:

15 bottles of merlot remaining

17 bottles of zinfandel remaining

32 bottles of sauvignon remaining

As you can see from the above examples, the foreach construct makes working with arrays much easier.

The principle of operation of the switch construction is somewhat similar to if - the result obtained when evaluating an expression is checked against a list of potential matches.

This is especially useful when checking multiple values, as using switch makes the program more descriptive and compact. The general format of the switch command is:

switch (expression) (

case (condition):

case (condition):

The condition to be checked is indicated in parentheses after the switch keyword. The result of its calculation is sequentially compared with the conditions in the case sections. If a match is found, the block of the corresponding section is executed. If no match is found, the optional default section block is executed.

As you will see in the following chapters, one of the strengths of PHP is handling user input. Let's say the program displays a drop-down list with several options and each line of the list corresponds to some command executed in a separate case construct. It is very convenient to build the implementation using the switch command:

$ user_input = "recipes"; // Command selected by user

switch ($ user_input):

case ("search"):

print "Let" s perform a search! ";

case ("dictionary"):

print "What word would you like to look up?";

case ("recipes"):

print "Here is a list of recipes ...";

print "Here is the menu ...";

As you can see from the above snippet, the switch command provides a clear and intuitive organization of the code. The variable specified in the switch clause (in this example, $ user_input) is compared with the conditions of all subsequent case sections. If the value specified in the case section matches the value of the compared variable, the block of this section is executed. The break statement prevents further case sections from being checked and terminates the switch statement. If none of the checked conditions are met, the optional default section is invoked. If there is no default section and none of the conditions are met, the switch command simply ends and program execution continues with the next command.

You must remember that if there is no break statement in the case section (see the next section), switch execution continues with the next statement until a break statement is encountered or the end of a switch statement is reached. The following example demonstrates the consequences of missing a forgotten break command: $ value = 0.4;

switch ($ value):

print "value is 0.4
";

print "value is 0.6
";

print "value is 0.3
";

print "You didn" t choose a value! ";

The result looks like this:

The absence of a break command resulted in not only the print command being executed in the section where the match was found, but also the print command in the next section. Then, the execution of the switch statements was interrupted by the switch statement following the second print statement.

The choice between the switch and if commands has practically no effect on the performance of the program. The decision to use this or that construction is rather a personal matter of the programmer.

The break statement immediately interrupts the execution of the while, for, or switch statement in which it is located. This command was already mentioned in the previous section, but interrupting the current loop does not exhaust the capabilities of the break command. In general, the break syntax looks like this:

The optional parameter n specifies the number of levels of control structures to be terminated by the break command. For example, if a break is nested within two while statements and the number 2 is after break, both loops are exited immediately. The default value for n is 1; going to one level can be indicated either by an explicit indication of 1, or by an indication of the break command without a parameter. Note that the i f command is not one of the control constructs interrupted by the break command.

Often you need to go through all the elements of a PHP array and perform some kind of operation on each element. For example, you can output each value to an HTML table, or you can assign a new value to each element.

In this lesson, we will look at the foreach construct when looping through indexed and associated arrays.

Loop over element values

The simplest use case for foreach is when looping over values ​​in an indexed array. Basic syntax:

Foreach ($ array as $ value) (// Do something with $ value) // Here the code is executed after the loop ends

For example, the following script loops through the list of directors in an indexed array and prints out the name of each:

$ directors = array ("Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang"); foreach ($ directors as $ director) (echo $ director. "
"; }

The above code will output:

Alfred Hitchcock Stanley Kubrick Martin Scorsese Fritz Lang

Loop over keys and values

What about associated arrays? When using this type of array, you often need to have access to the key of each element as well as its value. The foreach construct has a way to accomplish this task:

Foreach ($ array as $ key => $ value) (// Do something with $ key and / or $ value) // Here the code is executed after the loop ends

An example of organizing a loop through an associated array with information about movies, displays the key of each element and its value in the HTML definition list:

$ movie = array ("title" => "Rear Window", "director" => "Alfred Hitchcock", "year" => 1954, "minutes" => 112); echo "

"; foreach ($ movie as $ key => $ value) (echo"
$ key:
"; echo"
$ value
";) echo"
";

This script will output when executed:

Title: Rear Window director: Alfred Hitchcock year: 1954 minutes: 112

Changing the value of an element

But what about the change in the value of an element during the loop? You can try code like this:

Foreach ($ myArray as $ value) ($ value = 123;)

However, if you run it for execution, then you will find that the values ​​in the array do not change... The reason is that foreach works with a copy array values, not the original. This leaves the original array intact.

To change the values ​​of an array, you need link on the value. To do this, you need to put the & sign in front of the value variable in the foreach construction:

Foreach ($ myArray as & $ value) ($ value = 123;)

For example, the following script loops through each element of (director's name) in the $ directors array, and uses the PHP explode () function and the list construct to swap first and last names:

$ directors = array ("Alfred Hitchcock", "Stanley Kubrick", "Martin Scorsese", "Fritz Lang"); // Change the name format for each element foreach ($ directors as & $ director) (list ($ firstName, $ lastName) = explode ("", $ director); $ director = "$ lastName, $ firstName";) unset ( $ director); // Print the final result foreach ($ directors as $ director) (echo $ director. "
"; }

The script will output:

Hitchcock, Alfred Kubrick, Stanley Scorsese, Martin Lang, Fritz

Note that the script calls the unset () function to remove the $ director variable after the first loop has finished. This is a good practice if you plan to use the variable later in the script in a different context.

If you do not delete the link, then there is a risk in the further execution of the code of a random reference to the last element in the array ("Lang, Fritz"), if you continue to use the $ director variable, which will lead to unforeseen consequences!

Summary

In this tutorial, we looked at how to use the PHP foreach construct to loop through the elements of an array. The following issues were considered:

  • How to loop through the elements of an array
  • How to access key and value of each item
  • How to use a reference to change values ​​while walking through the loop