PHP foreach: Tutorials and Examples

by 14,286 views

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() 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():

Foreach Loop in PHP

There are two syntaxes of the foreach statement:

Hoặc

Recommended:
woocommerce_form_field() user guide and 10 sample examples
3 Ways to Get Post Content by ID & 11 Ways to Get Post ID in WordPress
These 70+ Specialized Blogs About WordPress Will Help Bloggers Succeed
wp_get_attachment_image_src() – a WordPress Function to Returns Array of Image Data

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

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() works on an associative array:

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.

The results will show up like this:

Another example of Loop through an array php using Nesting foreach loops

The result will show like this

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.

Result:

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 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.

The output of the example above will look like this:

remove an array element in a PHP foreach loop

Break a foreach loop in PHP

When using loops you may also end the loop or skip the current iteration

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 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:

Example 2:

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).

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 in php

The most common error is an error related to non-standard arrays or objects, so foreach cannot run.
When you feed a foreach 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 foreach, we will check if the object is an array or an object?

 

14,287 views
Share.
About Author