HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP foreach Loop


The foreach loop is a powerful and concise way to iterate through the elements of an array or object..



The foreach Loop on Arrays

The foreach loop is a powerful and versatile way to iterate through the elements of an array in PHP.


Example


Loop through the items of an indexed array:

<!DOCTYPE html>
<html>
<body>

<?php  
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $x) {
  echo "$x 
"; } ?> </body> </html>

Output

red
green
blue
yellow

For every loop iteration, the value of the current array element is assigned to the variabe $x. The iteration continues until it reaches the last array element.


• The foreach Loop on Objects

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

Example


Print the property names and values of the $myCar object:

<!DOCTYPE html>
<html>
<body>

<?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
"; } ?> </body> </html>

Output

color: red
model: Volvo

• The break Statement

With the break statement we can stop the loop even if it has not reached the end:

Example


<!DOCTYPE html>
<html>
<body>

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {
  if ($x == "blue") break;
  echo "$x 
"; } ?> </body> </html>

Output

red
green

• The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example


<!DOCTYPE html>
<html>
<body>

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {
  if ($x == "blue") continue;
  echo "$x 
"; } ?> </body> </html>

Output

red
green
yellow

• Foreach Byref

When looping through the array items, any changes done to the array item will, by default, NOT affect the original array:

Example


By default, changing an array item will not affect the original array:

<!DOCTYPE html>
<html>
<body>

<pre>
<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {
  if ($x == "blue") $x = "pink";
}

var_dump($colors);
?>
</pre>

</body>
</html>


Output

array(4) {
[0]=>
string(3) "red"
[1]=>
string(5) "green"
[2]=>
string(4) "blue"
[3]=>
string(6) "yellow"
}