The internal working of the ‘foreach’ loop in PHP


The ‘foreach’ loop in PHP helps in accessing key value pairs within an array. The ‘foreach’ loop works with arrays only, with the advantage that a loop counter wouldn’t need to be initialized. In addition to this, no condition needs to be set that would be needed to exit out of the loop. The ‘foreach’ loop implicitly does this too.

Example

 Live Demo

<?php
   $my_arr = array("Joe", "Hannah", "Paul", "Sanna");
   foreach($my_arr as $entry)
   {
      echo "$entry<br/>";
   }
?>

Output

Joe
Hannah
Paul
Sanna

An array of string values is defined and the foreach loop is used to access every element inside the array by giving a variable name. The ‘echo’ is used to display every element of the array on the console.

Updated on: 01-Jul-2020

214 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements