PHP foreach Loop

This YouTube video was created by Steve Griffith.

The foreach loop works best when you want to iterate over all the items in an associative array. Let's say we have an associative array people's id numbers. The label for each item is their name and the value of each item is their id number.

$people = ["Rick" => 223, "Admir" => 543, "Wendy" => 766, "Lucas" => 122]; 
foreach ($people as $key => $val) { 
  echo "The person {$key} has the value {$val} <br/>";
}

This will result in the following output.

The person Rick has the value 223<br/>
The person Admir has the value 543<br/>
The person Wendy has the value 766<br/>
The person Lucas has the value 122<br/>

The foreach loops use the name of the array to loop through followed by the as keyword. Next come two variable names that you make up. I chose to use the names $key and $val but you can use anything you want. Another common pair of names for the variables are $k and $v The first variable will hold the name of each item label (or key) as you loop through the array. The second variable holds the value of each item. If there are four items in the array then the loop will run four times.