The PHP foreach statement executes the command in an array or an object. Foreach loop in the array or object it will execute the statement once, doing so from the first loop to the last loop. Unless another command prevents or navigates PHP foreach.
foreach() loop appears in most popular CMS using PHP such as WordPress, Joomla, Laravel, Mambo,…
The PHP foreach statement executes only one statement for each element in the array.
Table of Contents
- 1 Syntax of PHP foreach():
- 2 Code & Explanation:
- 2.1 PHP Foreach() on Indexed arrays:
- 2.2 PHP Foreach() on an associative array:
- 2.3 Php Nested Foreach On Multi Dimensional Array
- 2.4 Find the foreach index
- 2.5 Count number of iterations in a foreach loop
- 2.6 Remove an array element in a foreach loop
- 2.7 Break a foreach loop in PHP
- 2.8 Modify an array within a PHP foreach loop
- 3 Performance of $key => $value
- 4 Some possible errors when using foreach loop in php
Syntax of PHP foreach():
There are two syntaxes of the PHP foreach statement:
foreach (iterable_expression as $value) { statement }
Or
foreach (iterable_expression as $key=>$value) { statement(s) }
Code & Explanation:
As we learned in the Syntax of PHP foreach()
section above, the foreach function can work on both indexed and associative arrays.
We will learn in turn how the PHP foreach function works on both these types of arrays.
We will first look at how the foreach()
function works on an indexed array.
PHP Foreach() on Indexed arrays:
Suppose we have an indexed array of fruits as follows $array_fruits
. Then we will run the PHP foreach function to display each fruit, one per line.
<?php $array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry"); foreach ($array_fruits as $value) { echo "$value <br>"; } ?>
The above syntax can be read as “for each element in array $array_fruits
accessed as $value
, execute echo and newline statement”. And here is the result
Apple Apricot Avocado Banana Berry Cantaloupe Cherry
At each iteration of the foreach loop, you can access the corresponding element of the array for that iteration, via the $value
variable. You can change the variable name $value
to whatever variable name you want. The example above if you don’t like $value
, you can set it to $fruit
for example.
Then the code will look like this:
<?php $array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry"); foreach ($array_fruits as $fruit) { echo "$fruit <br>"; } ?>
PHP Foreach() on an associative array:
Next we will learn how PHP Foreach() Loop works on an associative array:
<?php $football_teams = array("name" => "Ronaldo", "email" => "[email protected]", "age" => 36, "gender" => "male"); // Loop through employee array foreach($football_teams as $key => $value) { echo $key . ": " . $value . "<br>"; } ?>
As such, in an associative array, you will access the key and value in each iteration using the $key
and $value
variables. Similar to an indexed array, in an associative array you can also change the $key
and $value
variables to whatever you want.
As we have seen, associative arrays differ from indexed arrays in the sense that associative arrays use descriptive names for id keys. As the example above we have 4 keys corresponding to 4 values for the $football_teams
array
The example above will produce the following result
name: Ronaldo email: [email protected] age: 36 gender: male
Php Nested Foreach On Multi Dimensional Array
For PHP Multidimensional Arrays you can use nested foreach. The level of nested foreach statements is equal to the size of the multidimensional array.
Below is a two dimensional array and uses nested foreach to iterate through the elements of the array and display the results.
<?php $football_teams =array( "0" => array("name" => "Messy", "email" => "[email protected]", "age" => 34, "gender" => "male"), "1" => array("name" => "Ronaldo", "email" => "[email protected]", "age" => 36, "gender" => "male") ); foreach($football_teams as $key => $team_info) { $information = ''; foreach($team_info as $keyname => $team) { $information .= $keyname.": ".$team.", "; } echo "$key: $information<br />"; } ?>
The results will show up like this:
0: name: Messy, email: [email protected], age: 34, gender: male, 1: name: Ronaldo, email: [email protected], age: 36, gender: male,
Another example of Loop through an PHP array using Nesting foreach() loops
<?php $array2 = array( array(date('Y', strtotime("-12 months ".date('Y-m-d')."")), date('Y'), date('Y', strtotime("+12 months ".date('Y-m-d').""))), array(4, 5, 6), array(1, 2, 3) ); /* date('Y', strtotime("-12 months ".date('Y-m-d')."")) // Will show the previous year - like 2020 date('Y') // Will show the current year - like 2021 date('Y', strtotime("+12 months ".date('Y-m-d')."")) // Will show the next year - 2022 */ foreach ($array2 as $array1) { foreach ($array1 as $value) { echo $value; echo " "; } echo "<br>"; } ?>
The result will show like this
2020, 2021, 2022, 4, 5, 6, 1, 2, 3,
Find the foreach index
To find the foreach index, we just need to show the $key
. $key
is the index of each $array
element
For example:
Going back to the example with the array of fruits above. We will show get the index of the current iteration of a foreach loop and the corresponding value on each line.
<?php echo "Using foreach with index <br />"; $array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry"); foreach($array_fruits as $key=>$value) { echo "$key => $value.\n [=========>] Here \$key = $key, \$value = $value<br />"; } ?>
Result:
Using foreach with index 0 => Apple. [=========] Here $key = 0, $value = Apple 1 => Apricot. [=========] Here $key = 1, $value = Apricot 2 => Avocado. [=========] Here $key = 2, $value = Avocado 3 => Banana. [=========] Here $key = 3, $value = Banana 4 => Berry. [=========] Here $key = 4, $value = Berry 5 => Cantaloupe. [=========] Here $key = 5, $value = Cantaloupe 6 => Cherry. [=========] Here $key = 6, $value = Cherry
Count number of iterations in a foreach loop
If you want to count the total number of elements in the array in the foreach, you can use the index above, or use the count()
function to display the total.
$total = count($array_fruits);
Another way is to display all the values of each element with its position with $i
and $i++
<?php $i = 0; foreach ($array_fruits as $fruit) { $fruit[5];// Replace number with the number you want to display. For example if there are 7 $fruit in this foreach, I want get the value : 5, then it will be $fruit[5] $i++; } ?>
Remove an array element in a foreach loop
Use unset()
function to remove array elements in foreach loop. The unset() function is a built-in PHP function that is used to unset a specified variable.
First, we still use PHPforeach()
, then check the loop, if we encounter a value we need to delete, we will use the unset()
function to remove it. The loop continues to run after that without any effect.
<?php // Declare an array and initialize it $array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry"); // Display the array elements echo "<pre> "; print_r($array_fruits); echo " </pre>"; // Use foreach loop to remove array element foreach($array_fruits as $k => $fruit) { if($fruit == "Apple") { unset($array_fruits[$k]); } } // Display the array elements echo "This is array after remove Apple from \$array_fruits <pre> "; print_r($array_fruits); echo " </pre>"; ?>
The output of the example above will look like this:
Break a foreach loop in PHP
When using loops you may also end the loop or skip the current iteration
<?php $array_fruits = array("Apple", "Apricot", "Avocado", "Banana", "Berry", "Cantaloupe", "Cherry"); foreach($array_fruits as $key=> &$value) { echo "$key => $value.\n [=========] Here \$key = $key, \$value = $value<br />"; if($key == 3) // Only runs to the 4th loop ($key = 3 because $key starts at 0). You can compare $key < 3, it will only run 3 loops of 0.1, 2. The same goes for other comparisons of the if . function { break; } } ?>
Break will completely stop the execution of foreach at the time it reaches the specified requirement. This means that all subsequent iterations will no longer be able to execute the foreach statement.
Modify an array within a PHP foreach loop
If you are using foreach to iterate over an array and you want to modify the array itself, there are two ways to do it.
The first is to point to the array element you want to edit using the $array[$key]
syntax (so you have to use the foreach on an associative array $key => $value
syntax in the foreach).
Another way is to define $value
as a reference and edit it directly. Take a look at the two examples below:
Example 1:
$array = array(1000, 2000); foreach ($array as $key => $value) { $array[$key] += 100; } print_r($array);
Example 2:
$array = array(1000, 2000); foreach ($array as $key => &$value) { $value += 100; } print_r($array);
In both examples above, the result will be returned like this:
Array ( [0] => 1100 [1] => 2100 )
Performance of $key => $value
PHP Foreach loops support both $array
as $value
and $array as $key => $value
syntax. The first syntax has the fastest performance.
In my testing, using the second syntax resulted in 50% longer execution times. If you don’t need the key, you should probably use the first syntax.
Even so, the numbers are so small that you won’t notice any difference in real-life situations.
So don’t worry too much about performance (on my test machine, the two tests ran between 0.2 and 0.3 seconds, in an array of 10 million elements).
Summary
The $key => $value
in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,…
In PHP, associative arrays look like this:
Use foreach ($array as $element
) to iterate over the elements of an indexed array.
Use foreach ($array as $key => $value
) to iterate over the elements of an associative array.
Some possible errors when using foreach loop in php
The most common error is an error related to non-standard arrays or objects, so foreach loop cannot run.
When you feed a PHP foreach loop with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in
The workaround is extremely simple, that before launching the PHP foreach loop, we will check if the object is an array or an object?
if (is_array($array) || is_object($array)) { foreach ($array as $value) { // Do statement here } }