Using loops to iterate over array data is the easiest way to get at all
of the data inside an array for evaluating, parsing, or display. When you loop you
can access many key value pairs with just a few lines of code. You can
conduct any type of operations on the
key => value
pairs inside of your loops.
This is how we loop over and display data from a simple value based or
associative array:
<?php
$cart_array = array("Milk", "Cheese", "Eggs", "Cereal", "Jelly"); // has key increment index of 0
// To force key incrementing to start at 1 use this line instead to build your array
//$cart_array = array(1 => "Milk", "Cheese", "Eggs", "Cereal", "Jelly"); // Force key incrementing to start at 1
$i = 0; // create a varible that will tell us how many items we looped over
foreach ($cart_array as $key => $value) {
$i++; // increment $i by one each loop pass
echo "Cart Item $i ______ Key = $key | Value = $value<br />";
}
?>
Cart Item 1 ______ Key = 0 | Value = Milk
Cart Item 2 ______ Key = 1 | Value = Cheese
Cart Item 3 ______ Key = 2 | Value = Eggs
Cart Item 4 ______ Key = 3 | Value = Cereal
Cart Item 5 ______ Key = 4 | Value = Jelly
This is how we loop over and display data from a multidimensional array:
<?php
// create a multidimensional array that holds member details from our site
$members = array (
"member1" => array (
"name" => "John",
"zodiac" => "Scorpio",
"country" => "USA"
),
"member2" => array (
"name" => "Susan",
"zodiac" => "Virgo",
"country" => "Ireland"
),
"member3" => array (
"name" => "William",
"zodiac" => "Pisces",
"country" => "Great Britain"
),
"member4" => array (
"name" => "Eduardo",
"zodiac" => "Leo",
"country" => "Mexico"
)
);
$datasetCount = count($members); // returns count of array items of any array
echo "<h1>There are $datasetCount members</h1>";
$i = 0;
foreach ($members as $each_member) {
$i++;
echo "<h2>Member $i</h2>";
while (list($key, $value) = each ($each_member)) {
echo "$key: $value<br />";
}
}
?>
There are 4 members
Member 1
name: John
zodiac: Scorpio
country: USA
Member 2
name: Susan
zodiac: Virgo
country: Ireland
Member 3
name: William
zodiac: Pisces
country: Great Britain
Member 4
name: Eduardo
zodiac: Leo
country: Mexico