There are several ways to loop through all elements of an array in PHP. Here are the most common methods:
for
loop:$array = [1, 2, 3, 4, 5];
$length = count($array);
for ($i = 0; $i < $length; $i++) {
echo $array[$i] . "\n";
}
foreach
loop:$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
echo $value . "\n";
}
while
loop with the each()
function (Note: each()
is deprecated since PHP 7.2, so it's recommended to use foreach
instead):$array = [1, 2, 3, 4, 5];
reset($array); // Reset the array pointer
while (list(, $value) = each($array)) {
echo $value . "\n";
}
All these methods will output:
1
2
3
4
5
Choose the method that suits your requirements and coding style.