Foreach associative array

Foreach loop is of more use with associative arrays, because it gives access to both the key and value of each array element.

Foreach associative array syntax :

<?php
foreach (array_name as key_variable => value_variable)
{
do something with key_variable and value_variable
}
?>

array_name

This parameters used to store array.

key_variable

This parameters used to store array keys.

value_variable

This parameters used to array values.

Foreach associative array Example


<?php
$book ["title"] = "Dynamic Web Design Made Easy";
$book ["author"] ="David Powers";
$book ["Publisher"] ="friends of ED";
$book ["LSBN"] = "1-59059-720-19";
?>
<?php foreach ($book as $key => $value)
{
echo "The value of $key is $value";
}
?>

Out Put

The value of title is PHP Soluctions. Dynamic Web Design Made Easy
The value of author is David Powers
The value of Publisher is friends of ED
The value of LSBN is 1-59059-720-19

In the above example uses the $book associative array from the Creating arrays section.the associative array output will display keys and value .





Content