- PHP foreach() loop for indexed and associative arrays
- Table of Contents — PHP foreach:
- What is foreach in PHP?
- Syntax of PHP foreach():
- Code & Explanation:
- PHP Foreach() on Indexed arrays:
- PHP Foreach() on an Associative array:
- Closing thoughts:
- How to Find the foreach Index with PHP
- Applying the key Variable
- Applying the index Variable
- Applying the key and index Variables
- Describing the foreach Loop in PHP
- PHP foreach: Tutorials and Examples
- Syntax of PHP foreach():
- Code & Explanation:
- PHP Foreach() on Indexed arrays:
- PHP Foreach() on an associative array:
- Php Nested Foreach On Multi Dimensional Array
- Find the foreach index
- Count number of iterations in a foreach loop
- Remove an array element in a foreach loop
- Break a foreach loop in PHP
- Modify an array within a PHP foreach loop
- Performance of $key => $value
- Some possible errors when using foreach loop in php
PHP foreach() loop for indexed and associative arrays
In this tutorial, we look at the PHP foreach() loop. We also look at how to use it while working with an indexed or associative array.
Table of Contents — PHP foreach:
What is foreach in PHP?
The foreach() method is used to loop through the elements in an indexed or associative array. It can also be used to iterate over objects. This allows you to run blocks of code for each element.
Syntax of PHP foreach():
The foreach() method has two syntaxes, one for each type of array.
The syntax for indexed arrays is as given in the following code block:
foreach (iterable as $value) statement
The syntax for associative arrays:
foreach (iterable as $key => $value) statement
Here, “Iterable” is the required parameter. It is the array or the variable containing the array. “$value” is a variable that stores the current element in each iteration.
Associated array, uses keys and values, and hence the $key & $values in the second syntax represent the same accordingly.
Code & Explanation:
In this section, we first look at how the foreach() function works on an indexed array followed by which we look at it’s working on an associative array.
PHP Foreach() on Indexed arrays:
The output of the above code snippet would be:
Hire Top Freelance developers
PHP Foreach() on an Associative array:
"Eric", "email" => "[email protected]", "age" => 22, "gender" => "male" ); // Loop through employee array foreach($freelancer as $key => $value) < echo $key . ": " . $value . "
"; > ?>
The output of the above code snippet would be:
Now let’s look at a case where we pass a second argument.
As you can see the key and the values of the associative array were printed. Additionally, we replaced “=>” with a “:” to make it more readable.
Closing thoughts:
The foreach() method would return an error in case you use it on variables with a different data type. Additionally, the foreach() method does not modify the values of the internal pointer.
Once you have understood the working to the foreach() method try working with the for loop.
How to Find the foreach Index with PHP
In this tutorial, we provide you with helpful methods to find the foreach index in PHP.
Below, you can find three options with proper examples.
Applying the key Variable
The key variable contains the index of every value inside the foreach loop. In PHP, the foreach loop is used like this:
foreach ($arrayName as $value) < //code > ?>
The value variable contains the value of every element of the array. Here is an example:
$array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; foreach ($array as $key => $value) < echo "The index is = " . $key . ", and value is = " . $value; echo "\n"; > ?>
Here, the key variable stores the index of the foreach loop. The variable value demonstrates the value of every element within the array.
The output will look as follows:
The index is = 0, and the value is = 1 The index is = 1, and the value is = 2 The index is = 2, and the value is = 3 The index is = 3, and the value is = 4 The index is = 4, and the value is = 5 The index is = 5, and the value is = 6 The index is = 6, and the value is = 7 The index is = 7, and the value is = 8 The index is = 8, and the value is = 9 The index is = 9, and the value is = 10
Applying the index Variable
The index variable is applied as an additional variable for demonstrating the index of the foreach loop in any iteration.
// Declare an array $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $index = 0; foreach ($arr as $key => $val) < echo "The index is $index"; $index++; echo "\n"; > ?>
It is essential to consider that the index variable should initially be initialized with a value. Afterwards, it increments any time the loop iterates.
The output will look like this:
The index is 0 The index is 1 The index is 2 The index is 3 The index is 4 The index is 5 The index is 6 The index is 7 The index is 8 The index is 9
Applying the key and index Variables
Now, let’s see how using both the key and index variables will look like.
// Declare an array $arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; $index = 0; foreach ($arr as $key => $value) < echo "The index is $index"; $index = $key + 1; echo "\n"; > ?>
In the example above, the value of the key variable is kept with an increment within the index variable. So, in this case, both the key and index variables are used for finding the index of foreach.
Describing the foreach Loop in PHP
In PHP, the foreach loop is applied for looping through a block of code for every element inside the array. It is essential to note that the foreach loop only operates on objects and arrays. Once you try to use it on a variable with a different data type, it will issue an error.
PHP foreach: Tutorials and Examples
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.
Syntax of PHP foreach():
There are two syntaxes of the PHP foreach statement:
foreach (iterable_expression as $value)
foreach (iterable_expression as $key=>$value)
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.
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 Foreach() on an associative array:
Next we will learn how PHP Foreach() Loop works on an associative array:
"Ronaldo", "email" => "[email protected]", "age" => 36, "gender" => "male"); // Loop through employee array foreach($football_teams as $key => $value) < echo $key . ": " . $value . "
"; > ?>
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
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.
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
"; > ?>
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
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.
"; $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
"; > ?>
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.
Another way is to display all the values of each element with its position with $i and $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 PHP foreach() , 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.
"; print_r($array_fruits); echo "
«; // 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
"; print_r($array_fruits); echo "
«; ?>
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
&$value) < echo "$key =>$value.\n [=========] Here \$key = $key, \$value = $value
"; 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:
$array = array(1000, 2000); foreach ($array as $key => $value) < $array[$key] += 100; >print_r($array);
$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:
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).
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 >>