How to loop an array with the various loops in PHP?

In this tutorial, you will learn how to loop an array with the various loops (while, do-while, for, foreach) in PHP.

PHP array looping

Before going any further, you should know about the array_keys and count functions. Because these functions will be used to loop an array.

1. Numeric array with While Loop in PHP

<?php
$names = ['John', 'Mark', 'Bruce', 'Henry', 'Alen', 'Joe'];

$i = 0;
while($i < count($names)){
    echo $names[$i]."\n";
    $i++;
}
John
Mark
Bruce
Henry
Alen
Joe

2. Associative array with While Loop in PHP

<?php
$user = [
    "name" => "John",
    "email" => "[email protected]",
    "age" => 24
];

$userKeys = array_keys($user);

$i = 0;
while($i < count($userKeys)){
    echo $userKeys[$i] ." => ". $user[$userKeys[$i]]."\n";
    $i++;
}
name => John
email => [email protected]
age => 24

3. Numeric array with Do-While Loop in PHP

<?php
$names = ['John', 'Mark', 'Bruce', 'Henry', 'Alen', 'Joe'];

$i = 0;
do{
    echo $names[$i]."\n";
    $i++;
}while($i < count($names));
John
Mark
Bruce
Henry
Alen
Joe

4. Associative array with Do-While Loop in PHP

<?php
$user = [
    "name" => "John",
    "email" => "[email protected]",
    "age" => 24
];

$userKeys = array_keys($user);

$i = 0;
do{
    echo $userKeys[$i] ." => ". $user[$userKeys[$i]]."\n";
    $i++;
}while($i < count($userKeys));
name => John
email => [email protected]
age => 24

5. Numeric array with For Loop in PHP

<?php
$names = ['John', 'Mark', 'Bruce', 'Henry', 'Alen', 'Joe'];

for($i = 0; $i < count($names); $i++){
    echo $names[$i]."\n";
}
John
Mark
Bruce
Henry
Alen
Joe

6. Associative array with For Loop in PHP

<?php
$user = [
    "name" => "John",
    "email" => "[email protected]",
    "age" => 24
];

$userKeys = array_keys($user);

for($i=0; $i < count($userKeys); $i++){
    echo $userKeys[$i] ." => ". $user[$userKeys[$i]]."\n";
}
name => John
email => [email protected]
age => 24

7. Numeric array with Foreach Loop in PHP

<?php
$names = ['John', 'Mark', 'Bruce', 'Henry', 'Alen', 'Joe'];

foreach($names as $name){
    echo $name."\n";
}
John
Mark
Bruce
Henry
Alen
Joe

8. Associative array with Foreach Loop in PHP

<?php
$user = [
    "name" => "John",
    "email" => "[email protected]",
    "age" => 24
];

foreach($user as $key => $value){
    echo $key ." => ". $value."\n";
}
name => John
email => [email protected]
age => 24

Leave a Reply

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