Regarding code performance which is most advantageous, use foreach
or for
?
Example:
$array = array(1,2,3,4,5,6,7,8,9);
//assim
foreach($array as $value)
{
}
//ou assim
$count = count($array);
for($i=0;$i<$count;$i++)
{
}
Regarding code performance which is most advantageous, use foreach
or for
?
Example:
$array = array(1,2,3,4,5,6,7,8,9);
//assim
foreach($array as $value)
{
}
//ou assim
$count = count($array);
for($i=0;$i<$count;$i++)
{
}
Hello, about performance in relation to loops the most recommended to go through arrays is foreach because the performance of it is much higher than the traditional , you can check it out using a php function microtime () , foreach was done almost exclusively to traverse collections of data like the array. But not everything is flowers with foreach you can only go through the elements in a single direction, that is, growing from beginning to end of the collection, already with for you have the flexibility to go from beginning to end and vice versa. In short, you will use for or foreach depending on the application, not just for performance.
<?php
$n = array(2,1,4,6,45,7,45,3,23,465,67,77,88,234,432,5566,309,44,9,323,545,5656,6768,667,32,239,122,298);
$tot = count($n);
$t = microtime();
for($i = 0; $i < $tot; $i++) {}
echo "tempo do for: <br />",microtime() - $t,' segundos<br /><br />';
$t2 = microtime();
foreach($n as $v) {}
echo "tempo do foreach: <br />", microtime() - $t2,' segundos';
?>
I hope I have helped.