Tuesday, 21 July 2015

foreach in PHP

In PHP, foreach statement is used to iterate over collection of data, like PHP arrays. As per the name of this construct, it will keep on continue with the loop to traverse given input array for each of its element, without any condition.
We have slightly touch about 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 statementforeach contains no counters, conditions and no need of increments or decrements, explicitly. Rather, it will iterate with each element, and will be useful, where all the elements of
the array to be traversed unconditionally.
php_foreach

foreach Usage in PHP Script

We can use foreach statement in a PHP program with two various syntax differed based on the iteration behavior for getting array elements in the following type of ways.
  • For getting only array values.
  • For getting both key and value component of each element.

Getting Array Values

foreach syntax for getting only values of a given input array is as shown below.
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,
$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 foreachstatement follows. Inside foreach block each value of the array element is applied forPHP case conversion function ucfirst(), and stored into 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 default numeric array index.

Getting both key and value

In this method, we can iterate an array or object for getting the element as pair, on each iteration. And, we can use these keys instead of default numeric indices, while displaying resultant array to the browser. The syntax and example program for this method of using PHP foreach is given below which is slightly differed from the previous method.
foreach($input_array as $key=>$value) {
...
}
By using above foreach syntax, the key and value of $input_array is stored into the PHP variables, $key, $value, respectively. For example,
$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 shown below.
while (list(, $value) = each($input_array)) {
...
}
and
while (list($key, $value) = each($input_array)) {
...
}
But, the only difference is that, the PHP foreach is capable of resetting input array automatically, while start iterating over it. But, before using either of above alternative syntax, we need to call PHP reset() to reset 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 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 two dimensional input array, should be identical with the length of the input array.

0 comments:

Post a Comment