For Loop for Arrays in PHP
Suppose we have the following array:
<?php
$arr = [1, 2, 3, 4, 5];
?>
As you know, arrays are iterated using the foreach loop.
In fact, array elements can also be iterated
with a regular for loop. This is rarely needed,
but sometimes it can be useful. Let's
perform such an iteration:
<?php
$arr = [1, 2, 3, 4, 5];
$length = count($arr);
for ($i = 0; $i < $length; $i++) {
echo $arr[$i];
}
?>
Given an array:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
?>
Using a for loop, display all these
elements on the screen.
Given an array:
<?php
$arr = ['a', 'b', 'c', 'd', 'e'];
?>
Using a for loop, display
all elements of this array except the last one.
Given an array:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8];
?>
Using a for loop, display the
first half of the elements of this array.