Optimization Through Built-in Functions in PHP
Suppose a programmer checks if
the array contains the number 5:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$exists = false;
foreach ($arr as $elem) {
if ($elem == 5) {
$exists = true;
break; // exit the loop to avoid unnecessary iterations
}
}
var_dump($exists);
?>
I claim that there is something wrong with this code. What is it? We exit the loop after finding the number 3, right? The fact is, that built-in PHP functions always work an order of magnitude faster than similar custom code.
In our case, there is a function in_array
that solves the given task - and we should use
exactly this function:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var_dump(in_array(3, $arr));
?>
Moral: before solving a task, always check if there is a built-in PHP function for its solution.
In the following code, a programmer finds the sum of array elements. Optimize this programmer's solution.
Here is the code:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$sum = 0;
foreach ($arr as $elem) {
$sum += $elem;
}
echo $sum;
?>
In the following code, a programmer finds the product of array elements. Optimize this programmer's solution:
<?php
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
$res = 1;
foreach ($arr as $elem) {
$res *= $elem;
}
echo $res;
?>