• Tutorial List

How to Use PHP For Loop With Array?

Last updated May 15, 2020
How to Use PHP For Loop With Array

In this tutorial, you will learn how to use the PHP For Loop with an array. But, before the start, you should learn or you must have the knowledge of PHP for Loop.


PHP For Loop with Numeric Array

<?php
  $names = array("John", "Mark", "Robin", "Barry");

  // The count() function is used to count array elements
  $number_of_array_elements = count($names);

  for($i=0; $i < $number_of_array_elements; $i++){
      echo $names[$i]."<br>";
  }
?>
Browser Output
John
Mark
Robin
Barry

Example with Associative Array

If you want to use PHP for loop with an associative array, it is a bit complicated. To do this we will use the PHP array_keys() function.

The PHP array_keys() function returns an array that contains all the keys of the specified array.

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

  // collection of all the array keys
  $array_keys = array_keys($data);
  $number_of_array_elements = count($data);

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

  for($i=0; $i < $number_of_array_elements; $i++){
      $key = $array_keys[$i];

      echo '<tr>
          <td>'.strtoupper($key).'</td>
          <td>'.$data[$key].'</td>
      </tr>';
  }

  echo "</tbody></table>";
?>
Browser Output
ID 2
NAME Ervin Howell
USERNAME Antonette
EMAIL [email protected]
PHONE 010-692-6593 x09125
WEBSITE anastasia.net