mega

foreach construct in PHP 4, PHP 5

 
ForEach($array as $array){ echo $array;}
ForEach($array as $array){ echo $array;}
ForEach($array as $array){ echo $array;}

 
Overview
 

 
 
criteria 1
 
 
 
 
 


 


Bottom Line

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes: foreach (array_expression as $value) statement foreach (array_expression as $key => $value) statement   The […]

0
Posted April 13, 2013 by Bandish Patel

 
Full Article
 
 

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

 

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).

The second form will additionally assign the current element’s key to the $key variable on each iteration.

It is possible to customize object iteration.

 

Note:

When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

As foreach relies on the internal array pointer changing it within the loop may lead to unexpected behavior.

 

 

In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?></code></div>
</div>
</div>

Referencing $value is only possible if the iterated array can be referenced (i.e. if it is a variable). The following code won't work:

<?php
foreach (array(1, 2, 3, 4) as &$value) {
$value = $value * 2;
}
?></code></div>
<div>

 

 


Bandish Patel

 


0 Comments



Be the first to comment!


Leave a Response


(required)

Powered By Indic IME