PHP Foreach Loop

Foreach loop is used to loop through associative arrays in PHP, the loop ends when the last array key/value pair is reached. Let's create an associative array with animal names as keys and sounds those animals make as values.

$animals = array ( 'Antelope' => 'Snorts', 'Bat' => 'Screeches', 'Bear' => 'Roars', 'Dolphin' => 'Clicks', 'Goose' => 'Honks', 'Vulture' => 'Screams' );

We can then create foreach loop to iterate through all the key/value pairs in the array:

foreach ( $animals as $name => $sound ) { //$name is key, $sound is value echo $name.' '.$sound; } /* output: Antelope Snorts Bat Screeches Bear Roars Dolphin Clicks Goose Honks Vulture Screams */

We can also use $animals[ $name ] in place of the $sound, since the $animals is our actual array and $name represents the key and array [ $key ] gets us the value. The following would be the same as previous example:

foreach ( $animals as $name => $sound ) { //$name is key, $sound is value echo $name.' '.$animals[ $name ]; }

Alternately, we can also omit part of the loop if we were looking for values only, without needing the keys:

foreach ( $animals as $value ) { echo $value; } /* output: Snorts Screeches Roars Clicks Honks Screams */

Modifying Array Values by Reference

If we wanted to directly modify values within the array, we can do so by using the ampersand (&) before the value within foreach loop. This is called assigning value by reference:

$numbers = array(1, 2, 3, 4, 5); print_r( $numbers ); /* output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) */ foreach ($numbers as &$number) { $number = $number * 2; } print_r( $numbers ); /* output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 [4] => 10 ) */ unset( $number ); // break the reference with the last element

It is recommended to use unset() on the $number after we created a reference to it, otherwise the reference will remain, leading to unexpected behavior, that's why we used unset( $number ); after the loop.

Alternative Foreach Syntax

As with many other loops and conditional statements, PHP allows for alternative foreach syntax, by removing curly brackets and using colon and endforeach; instead.

<html> <title>Welcome to My Web Page</title> <body> <?php foreach ( $animals as $name => $sound ) : ?> <!-- do something --> <?php endforeach; ?> </body> </html>