• Tutorial List

PHP While Loop with Array

Last updated May 15, 2020
PHP While Loop with Array

Learn how to use PHP While Loop with an Array. In this tutorial, you will learn how to use while loop with a Numeric array and you also learn how to use the PHP while loop with an Associative Array.


How to use PHP While Loop with an Array?

While Loop with Numeric Array

count() – The count function is used to count array elements.

<?php
  $names = array("John","Mark","Sam","Barry","Martin");
  $number_of_array_elements = count($names);

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

While Loop with Associative Array

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

<?php
  $data = array("name" => "John", "age"=>21, "email"=>"[email protected]");
  $all_the_array_keys = array_keys($data);

  $i = 0;

  while($i < count($all_the_array_keys)){
      echo $all_the_array_keys[$i].' => '.$data[$all_the_array_keys[$i]]."<br>";
      $i++;
  }
?>
Browser Output
name => John
age => 21
email => [email protected]