Table of Contents
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>";
}
?>
Result View Example
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>";
}
?>
Result View Example
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>";
}
?>
Result View Example
Document in project
You can Download PDF file.