3 examples of PHP foreach loop to print array

What is PHP foreach loop?

The foreach is a type of loop that is used to loop through array elements. While developing PHP programs, you will come across arrays and its manipulation.

See an example of foreach

The PHP foreach loop makes it quite easier to get through array elements.

The foreach loop structure

Following is the structure of foreach loop:

foreach ($array_name as $value) {
Statements to execute;
}

The foreach with an array

In PHP, the foreach is used to loop arrays. The foreach loop passes the value of the current element which is assigned to $value while array pointer is moved to the next element. In the next loop, the next element will be processed and this will go on until the last element.

As you are using a foreach loop with an array, rather having a counter that goes until proven false (like i++) the foreach loop goes on looping unless it has used all values in the array.

A foreach PHP example with a numeric array

The following example creates an array of five numeric elements followed by a foreach that will loop through the array and will display array elements. Look how simple it is to use the foreach in PHP:

PHP foreach loop

Experience this example online



A foreach example with associative array

The following example creates an associative array with five elements for demo purpose. We will use the foreach loop to go through the array to display associative array elements.

PHP foreach

Experience this example online



How to print PHP array with echo and print

Printing an array as a whole or by elements is easy in PHP. We can use the echo or print statements to accomplish that.

PHP foreach echo

Experience this example online



 

See also PHP For Loop | PHP Do While Loop | PHP Arrays


Was this article helpful?

Related Articles

Leave A Comment?