foreach($array as $value) simply means, for every element in the array, assign its value to $value.
foreach($array as $key => $value) assigns the index of the array to $key and value of that index to $value.
:S I hope I am not confusing you!
This is almost similar to for loop.
for($i=0;$i<count($array);$i++) {
echo "Key is".$i."Value is".$array[$i];
}
//is same as
foreach($array as $key =>$value) {
echo "Key is".$key."Value is".$value;
}
nav33n
Purple hazed!
4,465 posts since Nov 2007
Reputation Points: 524
Solved Threads: 356
No probs! Btw, foreach is useful when you have irregular array indexes.
eg.
$array[3]=30; $array[10]=10; $array[11]=10;
nav33n
Purple hazed!
4,465 posts since Nov 2007
Reputation Points: 524
Solved Threads: 356
What does foreach($array as $value) test for? Or is it actually performing something similar to $value = $array[i]? Thanks for helping me clear this up!
Below is an example that will display all of the arrays and their values in the php format:
<?
$var['one']='aaa';
$var['two']='bbb';
$var['three']='ccc';
$var['four']='ddd';
$var['five']='eee';
foreach ($var AS $key => $value)
{
echo '$var[\''.$key."']=".$value.";";
}
?>
So what foreach basically does is loop through the array one array value at a time and assign the array value the the variable $value (in the example above) and the key (between the [] brackets) to the $key variable as shown in my example. Then those variables can be used in the loop while looping each value+key one at a time.
cwarn23
Occupation: Genius
3,033 posts since Sep 2007
Reputation Points: 413
Solved Threads: 259
foreach($array as $value) simply means, for every element in the array, assign its value to $value.
foreach($array as $key => $value) assigns the index of the array to $key and value of that index to $value.
:S I hope I am not confusing you!
This is almost similar to for loop.
for($i=0;$i<count($array);$i++) {
echo "Key is".$i."Value is".$array[$i];
}
//is same as
foreach($array as $key =>$value) {
echo "Key is".$key."Value is".$value;
}
You can try some examples here: http://www.php.net/foreach
http://www.tizag.com/phpT/foreach.php
evstevemd
Senior Poster
3,713 posts since Jun 2007
Reputation Points: 462
Solved Threads: 392