Jump to content

foreach


Mememe
 Share

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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...