In this tutorial, you will learn how to use PHP Do While Loop with an array and that array can be Numeric array or Associative array.


PHP Do While Loop with Numeric Array

First, we will see an example with a Numeric Array.

<?php
$names = ["Mark","John","Barry","kevin","Robert"];
$number_of_array_elements = count($names);
$i = 0;
do{
    echo $names[$i].'<br>';
    $i++;
}while($i < $number_of_array_elements);
?>
Browser Output
Mark
John
Barry
kevin
Robert

Example with an Associative Array

To use the Do While Loop with an Associative array we will use the same technique that we used on the PHP For Loop with an array chapter.

<?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);

$i = 0;
echo '<table border="1"><tbody>';

do{
    $key = $array_keys[$i];
    echo '<tr>
        <td>'.strtoupper($key).'</td>
        <td>'.$data[$key].'</td>
    </tr>';
    $i++;
}while($i < $number_of_array_elements);

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

Leave a Reply

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