➤ The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.
foreach ($array as $value) {
code to be executed;
}
For instance:
// array - $country
$country = ["Georia","Ukraine","Spain"];
foreach ($country as $value) { // Instead of name $value we can write any name
echo "$value \n";
}
/* outputs: Georia
Ukraine
Spain
*/
// array - numbers
$numbers = array("one" => 1 , "two" => 2 , "three" => 3 );
foreach($numbers as $n => $value) {
echo "$n = $value \n";
}
/*outputs: one = 1
two = 2
three = 3
*/
// also, we can print only keys/values
foreach($numbers as $n => $value){
echo "$n \n"; // if we need value of key, we must whrite $value
} // keys are "one","two","three" and values are 1,2,3
/*outputs: one
two
three
*/