Optimization of Array Conversion in PHP
It is not always necessary to split a string into an array to do something with it.
Let's look at an example.
In the next example, the code author checks
if the string contains the digit 3:
<?php
$str = '12345';
$arr = explode('', $str); // split into an array
if (in_array(3, $arr)) {
echo '+++';
} else {
echo '---';
}
?>
The author is great - they use PHP's built-in functions instead of writing their own crutches.
But the code is still not optimal: there is no
need to split the string into an array here, because there is
a ready-made function strpos that performs
search within a string:
<?php
$str = '12345';
if (strpos(str, 3) !== false) {
echo '+++';
} else {
echo '---';
}
?>
Why is splitting into an array bad here? Because, firstly, splitting into an array consumes CPU resources, and secondly, the resulting array will occupy space in RAM (and it will be more than the space occupied by the string itself).
Moral: do not split a string into an array if there is a way to avoid it.
In the following code, a certain programmer reverses the characters of a string. Optimize this programmer's solution:
<?php
$str = '123345';
$rev = implode('', array_reverse(explode('', $str)));
echo $rev; // will output '54321'
?>
In the following code, someone is looking for the number of words in a text. Optimize this programmer's solution:
<?php
$str = 'aaa bbb ccc'; // some long string
echo count(explode(' ', $str));
?>