your image

PHP foreach loop - javatpoint

javapoint
Related Topic
:- PHP Java computer programming

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 different datatype.

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

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

Syntax

  1. foreach ($array as $value) {  
  2.     //code to be executed  
  3. }  

There is one more syntax of foreach loop.

 

Features of Java - Javatpoint

Syntax

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

Flowchart

Example 1:

PHP program to print array elements using foreach loop.

  1. <?php  
  2.     //declare array  
  3.     $season = array ("Summer", "Winter", "Autumn", "Rainy");  
  4.       
  5.     //access array elements using foreach loop  
  6.     foreach ($season as $element) {  
  7.         echo "$element";  
  8.         echo "</br>";  
  9.     }  
  10. ?>  

Output:

SummerWinterAutumnRainy

Example 2:

PHP program to print associative array elements using foreach loop.

  1. <?php  
  2.     //declare array  
  3.     $employee = array (  
  4.         "Name" => "Alex",  
  5.         "Email" => "alex_jtp@gmail.com",  
  6.         "Age" => 21,  
  7.         "Gender" => "Male"  
  8.     );  
  9.       
  10.     //display associative array element through foreach loop  
  11.     foreach ($employee as $key => $element) {  
  12.         echo $key . " : " . $element;  
  13.         echo "</br>";   
  14.     }  
  15. ?>  

Output:

Name : AlexEmail : alex_jtp@gmail.comAge : 21Gender : Male

Example 3:

Multi-dimensional array

  1. <?php  
  2.     //declare multi-dimensional array  
  3.     $a = array();  
  4.     $a[0][0] = "Alex";  
  5.     $a[0][1] = "Bob";  
  6.     $a[1][0] = "Camila";  
  7.     $a[1][1] = "Denial";  
  8.       
  9.     //display multi-dimensional array elements through foreach loop  
  10.     foreach ($a as $e1) {  
  11.         foreach ($e1 as $e2) {  
  12.             echo "$e2\n";  
  13.         }  
  14.     }  
  15. ?>  

Output:

Alex Bob Camila Denial

Example 4:

Dynamic array

  1. <?php  
  2.     //dynamic array  
  3.     foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) {  
  4.         echo "$elements\n";  
  5.     }  
  6. ?>  

Output:

 

j a v a t p o i n t

Comments