PHP Foreach Loop

In this tutorial, you will learn how to use foreach loop to loops through a block of code for each element in an array.


The foreach loop is used to traverse through array elements and public properties of an object. It loops over by each element of an array and assigns the value of each element to $value.

It works only on the array and public properties of an object. If you try to use it with other data types, it will throw an error.

PHP Foreach Loop Syntax

<?php 
foreach (array as $value){ 
//code to be executed; 
} 
?>

PHP Foreach Loop Example

<?php 
//declare array 
$color = array ("Red", "Green", "Yellow", "Black","Pink"); 

//access array elements using foreach loop 
foreach ($color as $value) { 
echo "$value"; 
echo "<br />"; 
} 
?>

Output

Red
Green
Yellow
Black
Pink

Please get connected & share!

Advertisement