php-foreach_Loop

Back to ACP page

Table of Contents

Loop on Arrays

The most common use of the foreach loop, is to loop through the items of an array.

<h4>PHP foreach Loop - Loop_on_Arrays</h4> <p>The most common use of the foreach loop, is to loop through the items of an array.</p> <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $x) { echo "$x <br>"; } ?>

Example 1

Result View Example

Keys and Values

Print both the key and the value from the $members array:

<h4>PHP foreach Loop - Keys_and_Values</h4> <p>Print both the key and the value from the $members array:</p> <?php $members = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($members as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?>

Example 2

Result View Example

foreach Loop on Objects

The foreach loop can also be used to loop through properties of an object:

<h4>PHP foreach Loop - foreach Loop on Objects</h4> <p>The foreach loop can also be used to loop through properties of an object:</p> <?php class Car { public $color; public $model; public function __construct($color, $model) { $this->color = $color; $this->model = $model; } } $myCar = new Car("red", "Volvo"); foreach ($myCar as $x => $y) { echo "$x: $y <br>"; } ?>

Example 3

Result View Example

Document

Document in project

You can Download PDF file.

Reference