Unnecessary Array Length Calculation in a Loop in PHP
Let there be a given array with numbers:
<?php
$arr = [1, 2, 3, 4, 5];
?>
Let's make it so that each element of the
array is squared. That is, we should have
the same array $arr, but with
squared numbers.
In this case, the foreach loop is not suitable,
and we need a regular for loop for the array,
like this:
<?php
$arr = [1, 2, 3, 4, 5];
for ($i = 0; $i < count($arr); $i++) {
$arr[$i] = $arr[$i] * $arr[$i]; // change each array element
}
var_dump($arr);
?>
What's wrong with this code? The problem is
that count($arr) will be pointlessly
calculated on every loop iteration! Why,
because the array length doesn't change during the loop, right?
To optimize, let's move the calculation of the array length into a separate variable:
<?php
$arr = [1, 2, 3, 4, 5];
$len = count($arr); // optimize
for ($i = 1; $i < $len; $i++) {
$arr[$i] = $arr[$i] * $arr[$i];
}
var_dump($arr);
?>
Optimize the code below:
<?php
$arr = [1, 2, 2, 4, 5];
for ($i = 1; $i < count($arr); $i++) {
if ($arr[$i - 1] === $arr[$i]) {
echo $arr[$i] . '<br>';
}
}
?>