Hour Seven

Arrays

Listing 7.2 - Looping thru an Assoociative Array with foreach

$character is the array to loop through, $key is a variable that temporarily holds each key, and $value is a variable that temporarily holds each value.

<?php
$character = array (
			name=>"bob",
			occupation=>"superhero",
			age=>45,
			"special power"=>"x-ray vision" );
			
foreach($character as $key=>$val) {
	echo "$key = $val<br />";
	}//end foreach
?>

And the output from looping thru the array $character is:

name = bob
occupation = superhero
age = 45
special power = x-ray vision

Listing 7.3 - Looping thru a Multidimensional Array with foreach

Create two foreach loops. The outer loop accesses each element in the numerically indexed array $characters and places each one in $val. Because $val contains an associative array, you would loop through this and output each of its elements (which are temporarily stored in $key and $final_val) to the browser.

<?php
$characters = array (
			  	array(name=>"bob",
					occupation=>"superhero",
					age=>45,
					"special power"=>"x-ray vision" ),
			   	array(name=>"sally",
					occupation=>"superhero",
					age=>24,
					"special power"=>"superhuman strength" ),
				array(name=>"mary",
					occupation=>"arch villian",
					age=>63,
					"special power"=>"nano technology" ),
				); //end main array
				
foreach($characters as $val) {
	if(is_array($val)) {	
	foreach($val as $key=>$final_val) {
		echo "$key: $final_val<br />";
		}//end foreach
	echo "<br />";
	}//end foreach
else {
	echo "Not an array!";
	}//end else
}//end if is array
?>

And the output:

name: bob
occupation: superhero
age: 45
special power: x-ray vision

name: sally
occupation: superhero
age: 24
special power: superhuman strength

name: mary
occupation: arch villian
age: 63
special power: nano technology