PHP

PHP Menu

PHP

Foreach Loop - PHP Basics

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Increment is automatic.

The syntax for the PHP foreach loop is:

foreach ($array as $value) {
    code to be executed;
}

Here is an example of a foreach loop. It prints all the values of the array $colors.

<?php
$colors = array("red", "blue", "yellow");
foreach ($colors as $value) { echo "$value <br>"; }

Another example of the foreach loop used on an array with key-value pairs:

<?php
$age = array("Mark" => "26", "Jeff" => "22", "Raymond" => "33");
foreach($age as $x => $val) { echo "$x = $val <br>"; }

Exercise

Create an array named $cars with the following values: ("Volvo", "Volkswagen", "Toyota", "Ford"). Print the values of the array using the foreach loop.

<?php
$var = 123;
<?php
$cars = array("Volvo", "Volkswagen", "Toyota", "Ford"); foreach ($cars as $value) { echo "$value <br>"; };
{ "test_output_contains": [ { "expected":"Volvo", "error_message":"Sorry. Please try again." }, { "expected":"Volkswagen", "error_message":"Sorry. Please try again." }, { "expected":"Toyota", "error_message":"Sorry. Please try again." }, { "expected":"Ford", "error_message":"Sorry. Please try again." } ], "test_variable_exists": { "object":"$cars", "error_message":"Have you declared <code>$cars<\/code>?" }, "success_message":"Good job!", "error_message":"Please read the instructions again." }

Introduction

PHP Basics

PHP Advance

PHP OOP

PHP Functions and Methods