I have been programming in php for a long time. And I had the following doubt regarding the efficiency of the resources and the speed of how they behave.
My question is this:
Which function is more effective when traversing an array?
I was reading documentation where it indicates that foreach
it is made to traverse array. But the question is rather which one is more effective, either because it accesses fewer methods or because it is much more native.
Here is an example to make it easier to understand:
Example For:
<?php
$colors = array("red", "green", "blue", "yellow");
$cantidad = count($colors);
for ($i = 0; $i <= $cantidad $i++) {
echo $colors[$i]."<br>";
}
?>
Foreach example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo $value."<br>";
}
?>
I appreciate the interest!
NOTE:
I keep in mind that at the level of just a couple of data, this is not reflected. But the idea is to present it at the level of many data
NOTE2:
As part of a response to the fact that the process would slow down if I for
placed it in my cycle count($colors)
, I have decided to separate it so that only the for itself is measured, and not the one that enters unnecessary methods.
To go through an array in PHP, and we are talking about rather large arrays, like 10 thousand iterations, the most efficient will be with foreach.
I leave you an example of execution.
NOTE:
In case of changing the following line
thus:
The change is noticeable considerably. And therefore ends up having a better cycle performance
for
With this simple algorithm you could calculate the time it takes each loop to go through the same elements.
Having first a
Array
with 10,000 random values ofString
:We will use the two loops to do the time tests with the use of the functions
microtime
:Finally we print the results:
Depending on the computer that runs the program you will get some results or others, but visibly it seems that the
foreach
is somewhat faster than thefor
.My result:
Here is the full test code
There is a published benchmark on this and the conclusion is as follows:
In all cases the loop
foreach
is substantially faster than thefor
and procedureswhile ()
.Based on your own codes and making variation to increase the
array
and also make last modification to place separately$contar = count($colors);
Code:
I leave the results since they did not update previous answers. And I leave the results where every time the cycle
for
always came out better. Thanks to @Voiser for being pro-active with this topic