foreach in PHP

by Vincy. Last modified on July 9th, 2022.

In PHP, foreach statement is used to iterate over a collection of data, like PHP arrays. As per the name of this construct, it will keep on continue with the loop to traverse the given input array for each of its elements, without any condition.

We have slightly touched on how this is working in PHP while seeing about PHP loops. In this article, let us see about foreach statement with more details.

Unlike other PHP loop statements, while, do..while and for, this PHP loop statement foreach contains no counters, conditions and no need for increments or decrements, explicitly. Rather, it will iterate with each element and will be useful, where all the elements of the array are to be traversed unconditionally.

foreach Usage in PHP Script

We can use foreach statement in a PHP program with two various syntaxes that differ based on the iteration behavior for getting array elements in the following type of ways.

  • For getting only array values.
  • For getting both the key and value of each element.

Getting Array Values

foreach syntax for getting only values of a given input array is as shown below.

<?php
foreach ($input_array as $value) 
{
    
}
?>

By using this foreach syntax the value of each $input_array element will be stored into $value, for each iteration, and, the array pointer will be moved to point next element of $input_array, to be iterated subsequently. For example,

<?php
$input_array = array(
    "apple",
    "orange",
    "grapes"
);
foreach ($input_array as $value) {
    $caps_value_array[] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_value_array);
print "</pre>";
?>

In the above PHP example program, there is an input array to be used for the foreach statement follows. Inside foreach block, each value of the array element is applied for PHP case conversion function ucfirst(), and stored in a new array. And the output of this program with the array values is shown below.

Getting Array Values
Array
(
    [0] => Apple
    [1] => Orange
    [2] => Grapes
)

Since we have iterated only the value of given $input_array, these values are displayed with the default numeric array index.

Getting both key and value

In this method, we can iterate an array or object for getting the element as <key, value> pair, on each iteration. And, we can use these keys instead of default numeric indices, while displaying the resultant array to the browser.

The syntax and example program for this method of using PHP foreach is given below which is slightly different from the previous method.

&lt;?php
foreach ($input_array as $key =&gt; $value) 
{
    
}
?&gt;

By using the above foreach syntax, the key and value of $input_array are stored in the PHP variables, $key, $value, respectively. For example,

<?php
$input_assoc_array = array(
    "fruit1" => "apple",
    "fruit2" => "orange",
    "fruit3" => "grapes"
);
foreach ($input_assoc_array as $key => $value) {
    $caps_assoc_array[$key] = ucfirst($value);
}
print "<b>Getting Array Values</b>";
print "<pre>";
print_r($caps_assoc_array);
print "</pre>";
?>

This kind of usage is mainly for iterating associative arrays in PHP. And the output of this program will be as follows.

Getting Array Values
Array
(
    [fruit1] => Apple
    [fruit2] => Orange
    [fruit3] => Grapes
)

Alternative PHP Syntax Replicating foreach Functionality

Both of the above foreach functionalities can also be obtained by using PHP while statements are shown below.

<?php
while (list (, $value) = each($input_array)) 
{
    
}
?>

and

<?php
while (list ($key, $value) = each($input_array)) 
{
    
}
?>

But, the only difference is that the PHP foreach is capable of resetting the input array automatically while starting iterating over it. But, before using either of the above alternative syntaxes, we need to call PHP reset() to reset the array pointer to the initial position.

Caution:

  • foreach PHP construct only supports data with array or object data type. Passing neither of these data types will cause PHP warning error.
    Warning: Invalid argument supplied for foreach() in ... on line ...
    
  • PHP errors that occurred during failure of foreach execution, will not be controlled by using @ operator.
  • We can iterate with an input array having more than one dimension. The length of the list given to store elements of a two-dimensional input array should be identical to the length of the input array.

Download PHP foreach Source Code

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page