• Tutorial List

PHP ForEach Loop

Last updated May 15, 2020
PHP ForEach Loop

The PHP ForEach loop is specifically made for arrays and objects, that means ForEach Loop works only on arrays and objects.

The PHP ForEach loop is very helpful (easy) if you want to loop an array or object.


Syntax of the ForEach loop

<?php
  foreach($array_or_object as $value){
      //statement
  }
?>

Example of the ForEach loop

<?php
  $users = array(
      'John',
      'Mark',
      'Barry',
      'Bruce',
      'Tony'
  );

  foreach($users as $value){
      echo $value.'<br>';
  }
?>
Browser Output
John
Mark
Barry
Bruce
Tony

Accessing keys of the Array or Object using ForEach Loop

So now we will see how to access the keys of the array or object by using the PHP ForEach Loop.

<?php
  foreach($array_or_object as $key => $value){
      echo $key.'<br>';
  }
?>

Example:

<?php
  $data = array(
      "id" => 2,
      "name" => "Ervin Howell",
      "username" => "Antonette",
      "email" => "[email protected]",
      "phone" => "010-692-6593 x09125",
      "website" => "w3jar.Com"
  );

  echo '<table border="1"><tbody>';

  foreach($data as $key => $value){
      echo '<tr>
          <td>'.strtoupper($key).'</td>
          <td>'.$value.'</td>
      </tr>';
  }

  echo "</tbody></table>";
?>
Browser Output
ID2
NAMEErvin Howell
USERNAMEAntonette
EMAIL[email protected]
PHONE010-692-6593 x09125
WEBSITEw3jar.Com