Php Foreach Loop With Example


The PHP Foreach loop statement only works with arrays and objects.PHP provides the Foreach loop statement that allows you to iterate over elements of an array or public properties of an object. If you use the Foreach loop statement with other data types, so, you will get an error.

PHP Foreach – loop iterate over elements of an indexed array.

To loop over elements of an indexed array, you use the following syntax:

<?php
foreach ($array as $element) {
 // process element here; Ex. echo  $element
}
foreach( $array as $key => $element) {
    // PHP Code to be executed
}

PHP assigns each element of the indexed array to the $element variable in each iteration. See the following example:

<?php
$numbers= [1,2,3];
foreach ($numbser as $number) {
 echo $number; // Ex. 1,2,3
}

Program 1: PHP program to print the array elements using Foreach loop.

<?php 
  
// Declare an array 
$arr = array("green", "blue", "pink", "white");  
  
// Loop through the array elements 
foreach ($arr as $element) { 
    echo "$element "; 
} 
  
?>

Output: 

green blue pink white


Program 2: PHP program to print the associative array elements using Foreach loop.

<?php  
$users= array(  
    "name" => "Ajay kumar",  
    "email" => "ajaykumar@mail.com",  
    "age" => 18,  
    "gender" => "male"
  
);  
  
// Loop through employee array  
foreach($users $key => $user) {  
    echo $key . ": " . $user. "<br>";  
}

Output:

name: Ajay kumar
email: ajaykumar@mail.com
age: 18
gender: male


I hope it can help you...

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close