Jump to content

foreach


Mememe

Recommended Posts

Foreach loops through each element in an array, and each iteration stores the current element to a variable. So, say we had an array of trangle numbers up to 6, the following code would loop through the array and ech time echo the element the foreach loop is examining

$triNums = array(1, 3, 6, 10, 15, 21);foreach ($triNums as triNum) {echo "$triNum, ";}

This will echo "1, 3, 6, 10, 15, 21".

Link to comment
Share on other sites

Foreach loops through each element in an array, and each iteration stores the current element to a variable. So, say we had an array of trangle numbers up to 6, the following code would loop through the array and ech time echo the element the foreach loop is examining
$triNums = array(1, 3, 6, 10, 15, 21);foreach ($triNums as triNum) {echo "$triNum, ";}

This will echo "1, 3, 6, 10, 15, 21".

I kind of get the idea, though I'm confused on the "as triNum" part.
Link to comment
Share on other sites

That means that each element is stored to the $triNum variable as it comes up - I made a typo, it should be as $triNum not as triNum !

Link to comment
Share on other sites

You can also use foreach to get both the index and the value of each element. Run this code and see what happens:

<?php$test_array = array(  'name' => 'Steve',  'city' => 'Phoenix',  'age' => 28);foreach ($test_array as $key => $value){  echo "key: {$key}; value: {$value}<br>";}?>

More information here:http://www.php.net/manual/en/control-structures.foreach.php

Link to comment
Share on other sites

You can also use foreach to get both the index and the value of each element. Run this code and see what happens:
<?php$test_array = array(  'name' => 'Steve',  'city' => 'Phoenix',  'age' => 28);foreach ($test_array as $key => $value){  echo "key: {$key}; value: {$value}<br>";}?>

More information here:http://www.php.net/manual/en/control-structures.foreach.php

I kind of understand now. Does $key have to be key, or I can use any name for it with the $ first right?
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...