How does the foreach loop work in php. PHP foreach loop: two ways to use it

do while and foreach loops

do loop . . while

do...while loop in C# this is a version of while with a post-condition check. 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 a do-while loop statement:

do (operators; ) while (condition);

If there is only one operator, curly braces in this form of notation are optional. 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 a do-while loop is the following program, which 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 a number 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 elements of a collection, which is a group of objects. C# defines several types 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) statement;

Here type loop_variable_name denotes the type and name of the loop control variable that receives the value next element collections at each step of the foreach loop. And collection denotes a cyclically queried collection, which hereinafter represents 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 may be useful for working with certain types 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 iteration step, the next array element is selected and stored in a loop variable. The loop ends when all elements of the array are selected.

A foreach loop allows you to iterate through each element of a collection (an object that represents a list of other objects). Technically, 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.

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 that should be executed)

Example of using a foreach loop with a numeric array

In this example, we will create an array of five elements 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 array values:

View demo and code

Example with array keys and values

This example describes another way to use the PHP foreach loop. To do this, we created an associative array of three elements. It includes the names of employees ( as keys) and the amount of 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 can change the values ​​of array elements. To do this, use "&" before "$" for value variable. For example:

&$value_of_element

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

In this example, we 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 elements of the array.

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 applying it as the max operator. But foreach makes it easier since it is designed to work with arrays.

If you work with MySQL, then this cycle is even more suitable for this. For example, you can select several rows from a database table and pass them into an array. After that, using a foreach loop, iterate through 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 the PHP foreach loop in PHP. Both are described below.

  • The syntax for the first method is:

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

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

For each iteration, the value of the current element is assigned to the $value variable. After the iteration is completed, the variable is assigned the value of the next element. And so on until all the elements of the array have been iterated.

  • 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, 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

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.

On in simple language it will sound something like this:
"For each element in the specified array, execute this code."

While it will continue as long as some condition is met, the foreach loop will continue until it has gone through every 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 ages. We want to know how old each employee is, so we use a for-each loop to print out everyone'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 construct 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 to: “For each element associative array$employeeAges I want to refer to $key and the value in it, i.e. $value.

The "=>" operator represents the 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. Below in our example we will do this, and note that the result will be the same because we only changed the names of the variables that relate to the 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.

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

In this lesson we will look at the foreach construct when organizing a loop over indexed and associated arrays.

Loop through element values

The simplest use case for foreach is to loop through values ​​in an indexed array. Basic syntax:

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

For example, the following script iterates 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

Key-Value Loop

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 solve the problem:

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

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

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

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

When executed, this script will output:

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

Changing the value of an element

What about changing the value of an element as the loop goes through? You can try this code:

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

However, if you run it, 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 way the original array remains intact.

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

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

For example, the following script loops through each element (director name) in the $directors array, and uses PHP function explode() and the list construct to change the places of the 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 completes. This is a good practice if you plan to use the variable later in the script in a different context.

If you don't remove the reference, you run the risk of further executing code accidentally referencing the last element in the array ("Lang, Fritz") if you continue to use the $director variable, which will lead to unintended consequences!

Summary

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

  • How to loop through array elements
  • How to access the key and value of each element
  • How to use a reference to change values ​​as you go through a loop

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 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, in otherwise, it is preferable to use .

For Each...Next Loop Syntax

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

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

Components of a For Each... Next Loop

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

**If you don't use your own code in a loop, the meaning of using a loop is lost.

Examples of For Each...Next loops

Loop over a range of cells

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

Sub test1() Dim element As Range, a As String a = "Data obtained by 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 many cells are selected, then complete information on all cells will not be displayed, since the maximum length of the parameter Prompt is approximately 1024 characters.

Loop for a collection of sheets

Copy the following VBA procedure to Excel workbooks:

Sub test2() Dim element As Worksheet, a As String a = "List of sheets contained in this worksheet:" 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 in the Excel workbook by the serial number of their labels corresponding to their indexes.

Loop for an array

Let's assign a list of animal names to the array and write them into a variable in the For Each... Next loop a. The MsgBox information window will display a list of animal names from the variable a.

Sub test3() Dim element As Variant, a As String, group As Variant group = Array("hippopotamus", "elephant", "kangaroo", "tiger", "mouse") "or you can assign the values ​​of the range of cells of the "worker" to the array sheet, for example, selected: 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 assign the value "Parrot" to all elements of the array in the For Each...Next loop. The MsgBox information window will display a list of animal names, consisting only of parrots, which proves that it is possible to edit the values ​​of 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") "or you can assign the values ​​of the range of cells of the "worker" to the array 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 all others in this article, was tested in Excel 2016.

Loop through a collection of subdirectories and exit the loop

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

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

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

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

Internet