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.

While Loop with Numeric Array

In the following example, I used the while loop with a 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

In the following example, I used the while loop with an 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]

Leave a Reply

Your email address will not be published. Required fields are marked *