phpicoder Nov 2, 2021 php

Hi guys, in this tutorial we will learn how to use PHP foreach loop statement to loop over elements of an array or public properties of an object.

We use the forech loop primarily for looping through array values. It loops over the array, and each value for the current array element is assigned a value, and the array pointer is moved one by one to move to the next element in the array. Although the forch loop is repeated on an array of elements, the execution is simplified when the loop is compared and the loop is finished in less time.

Foreach provides the easiest way to repeat construct array elements. It works on both arrays and objects. Although the fork loop is reverted to an array of elements, the execution is simplified and comparatively finishes the loop in less time. It allocates temporary memory for index iterations which makes the system as a whole redundant its performance in terms of memory system allocation.

foreach supports repetition on three different types of values:

Arrays
Normal objects
Traversable objects


PHP Foreach have a 2 syntext 

Syntax 1:
foreach($array as $value) {
    // PHP Code to be executed
}

 

Syntax2:

foreach($array as $key => $value) {
    // PHP Code to be executed
}

Example1 : 

<?php
  //declare array
  $langs = array ("php", "java", ".net", "html","css","js");

  //access array elements using foreach loop
  foreach ($langs as $value) {
  	echo "$value";
  	echo "</br>";
  }  
?>
Output:
php
java
.net
html
css
js

Example2 : 

<?php
  //declare array
  $student = array (
  	"Name" => "Andy",
  	"Roll No" => "20",
  	"Age" => 31,
  	"Gender" => "Male"
  );

  //display associative array element through foreach loop
  foreach ($student as $key => $value) {
  	echo $key . " : " . $value;
      echo "</br>";
    }  
?> 
Output:
Name : Andy
Roll No : 21
Age : 31
Gender : Male

I hope this tutorial help for you.