Menu
Is free
registration
home  /  Firmware/ PHP foreach loop: two ways to use it. Do while and foreach loops Php foreach arrays

PHP foreach loop: two ways to use it. Do while and foreach loops Php foreach arrays

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.

V this lesson we'll 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 these types of arrays, it is often necessary 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 with 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 variable value in the foreach construct:

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

For example, the following script loops through each item (director name) in the $ directors array, and uses PHP function explode () and the list construction 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 PHP construct foreach to loop through the elements of the 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

Imagine you have an associative array that you want to iterate over. PHP provides an easy way to use each element of an array in turn using the Foreach construct.

In plain language, it would sound something like this:
"For each element in the specified array, execute this code."

While it will continue until some condition is met, the foreach loop will continue until it goes through each element of the array.

PHP Foreach: Example

We have an associative array that stores the names of people in our company, as well as their age. We want to know how old each employee is, so we use a loop through each item to print out each employee's name and age.

$ employeeAges; $ employeeAges ["Lisa"] = "28"; $ employeeAges ["Jack"] = "16"; $ employeeAges ["Ryan"] = "35"; $ employeeAges ["Rachel"] = "46"; $ employeeAges ["Grace"] = "34"; foreach ($ employeeAges as $ key => $ value) (echo "Name: $ key, Age: $ value
"; }

We get the result:

Name: Lisa, Age: 28 Name: Jack, Age: 16 Name: Ryan, Age: 35 Name: Rachel, Age: 46 Name: Grace, Age: 34

Well, the result is good and understandable, but the syntax of the foreach construction is not very easy and understandable. Let's take a closer look at it.

For each syntax: $ something as $ key => $ value

All this madness roughly translates into: “For each element of the $ employeeAges associative array, I want to refer to $ key and the value in it, that is, $ value.

The "=>" operator represents a relationship between a key and a value. In our example, we named them as key - $ key and value - $ value. However, it would be easier to think of them as name and age. In our example below, we will do so, and note that the result will be the same, because we only changed the names of the variables that refer to keys and values.

$ employeeAges; $ employeeAges ["Lisa"] = "28"; $ employeeAges ["Jack"] = "16"; $ employeeAges ["Ryan"] = "35"; $ employeeAges ["Rachel"] = "46"; $ employeeAges ["Grace"] = "34"; foreach ($ employeeAges as $ name => $ age) (echo "Name: $ name, Age: $ age
"; }

Well, the result, we repeat, is the same.

The PHP foreach loop can be used like this:

foreach ($ array_name as $ value) (// code to be executed)

foreach ($ array_name as $ key => $ value) (// // code to be executed)

Example using a foreach loop with a numeric array

In this example, we will create a five-element array with numeric values. The PHP foreach loop will then be used to iterate through this array. Inside the foreach loop, we used echo to print out the values ​​of the array:

View demo and code

Example with keys and array values

This example describes another way to use the PHP foreach loop. For this, we have created an associative array of three elements. It includes the names of employees ( as keys) and the amount wages (as values):

View demo and code

An example of changing the value of an array element in a foreach loop

You can also c using PHP array foreach you can change the values ​​of array elements. To do this, use "&" before "$" for the variable value. For example:

& $ value_of_element

The value will be changed. To make it clearer, consider the following example.

In this example, we have created a numeric array of five elements. After that, we used a foreach loop to display the values ​​of the elements.

Then we created another foreach loop where "&" is added before $ value_of_element. Inside the curly braces, we assign new values ​​to the array elements.

To see the difference before and after assigning new values, the array is displayed using the print_r () function.

View demo and code

What is the PHP foreach loop used for?

The PHP foreach loop is used to work with an array. It iterates over each of its elements.

You can also use a for loop to work with arrays. For example using the length property to get the length of an array and then apply it as the max operator. But foreach makes it easier because it is designed to work with arrays.

If you are working with MySQL, then this cycle is even more suitable for this. For example, you can select multiple rows from a database table and pass them to an array. After that, using a foreach loop, iterate over all the elements of the array and perform some action.

Note that you can use a foreach loop with an array or just an object.

Using a foreach loop

There are two ways to use PHP foreach loop in PHP. Both are described below.

  • The syntax for the first usage method is:

foreach ($ array_name as $ value) (echo $ value)

In this case, you need to specify the name of the array, and then the variable $ value.

For each iteration, the value of the current element is assigned to the $ value variable. Upon completion of the iteration, the variable is assigned the value of the next element. And so on until all the elements of the array are enumerated.

  • The syntax of the second method ( PHP foreach as key value):

This is suitable for associative arrays that use key / value pairs.

During each iteration, the value of the current element will be assigned to the $ value_of_element variable. In addition, the element key is assigned to the $ key_of_element variable.

If you are working with numeric arrays, then you can use the first method, which does not require element keys.

This publication is a translation of the article " PHP foreach loop 2 ways to use it"Prepared by the friendly project team

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 for different types 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 from 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 for a switch command is:

switch (expression) (

case (condition):

case (condition):

The checked condition is indicated in parentheses after keyword switch. 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 separate design case. 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 variable being compared, the block of this section is executed. The break statement prevents further case sections from being checked and terminates the execution of 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 should 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 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. V general view 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 command 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.

For Each ... Next loop in VBA Excel, its syntax and description of the 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 in relation 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]

The brackets indicate the optional attributes of the For Each ... Next loop.

For Each ... Next Loop Components

*If For loop Each ... Next is used in VBA Excel to traverse 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 to 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 information window MsgBox 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 elements of the array 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 from 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 the 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 inclusively and the message of the cycle about the termination of its work.

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