#4 - PHP foreach loop
PHP foreach loop is an exclusive construct in PHP that iterates over arrays and objects only. It is highly efficient for looping over associative arrays. That’s because it reserves two pointers for accessing the key-value pairs as it loops over the associative array. Here’s the syntax.
foreach($associative_arr as $key=>$value) |
---|
The $key and $value get the associative array’s key and values as the loop iterates.
Source
https://www.php.net/manual/en/control-structures.foreach.php
xxxxxxxxxx
26
<?php
//An array with employee names as keys and their ages as values
$employee_age = array(
"Rachel" => 22,
"Edward" => 23,
"Simon" => 24,
"Anna" => 25,
"Mike" => 26
);
//Name is the key and age is the value
foreach($employee_age as $name=>$age)
{
echo $name." is ".$age." years old.".PHP_EOL;
}
/*
Rachel is 22 years old.
Edward is 23 years old.
Simon is 24 years old.
Anna is 25 years old.
Mike is 26 years old.
*/
?>
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment