Monday, March 1, 2021

PHP Tutorial Part 17 : PHP foreach loop

PHP foreach loop

The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of the different datatype.

The foreach loop works based on an element rather than an index. It provides the easiest way to iterate the elements of an array.

In the foreach loop, we don't need to increment the value.

Syntax

foreach ($array as $value) {  
    //code to be executed  
}  

There is one more syntax of the foreach loop.

Syntax

foreach ($array as $key => $element) {   
    //code to be executed  
}  



Example 1:

PHP program to print array elements using a foreach loop.

<?php  
    //declare array  
    $season = array ("Summer""Winter""Autumn""Rainy");  
      
    //access array elements using foreach loop  
    foreach ($season as $element) {  
        echo "$element";  
        echo "</br>";  
    }  
?>  

Output:

Summer 
Winter 
Autumn 
Rainy

Example 2:

PHP program to print associative array elements using a foreach loop.

<?php  
    //declare array  
    $employee = array (  
        "Name" => "onlinequizstock",  
        "Email" => "onlinequizstock@gmail.com",  
        "Age" => 22,  
        "Gender" => "Male"  
    );  
      
    //display associative array element through foreach loop  
    foreach ($employee as $key => $element) {  
        echo $key . " : " . $element;  
        echo "</br>";   
    }  
?>  

Output:

Name : onlinequizstock
Email : onlinequizstock@gmail.com
Age : 22
Gender : Male

Example 3:

Multi-dimensional array

<?php  
    //declare multi-dimensional array  
    $a = array();  
    $a[0][0] = "Alex";  
    $a[0][1] = "Bob";  
    $a[1][0] = "Camila";  
    $a[1][1] = "Denial";  
      
    //display multi-dimensional array elements through foreach loop  
    foreach ($a as $e1) {  
        foreach ($e1 as $e2) {  
            echo "$e2\n";  
        }  
    }  
?>  

Output:

Alex Bob Camila Denial

Example 4:

Dynamic array

  1. <?php  
  2.     //dynamic array  
  3.     foreach (array ('o''n''l''i''n''e''q''u''i''z'as $elements) {  
  4.         echo "$elements\n";  
  5.     }  
  6. ?>  

Output:

onlinequiz



Previous Post
Next Post

post written by:

0 Comments: