FOREACH or FOR?

Asked

Viewed 131 times

1

Regarding code performance which is more 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++)
{
}
  • The answer to this other similar question might help you: http://answall.com/questions/63005/qual-possuí-um-performant-bestfor-ou-foreachrange

1 answer

4


Hello, about performance in relation to loops the most recommended to go through arrays is the foreach because his performance is far superior to that of for traditional, you can check this using a php function, microtime(), the foreach was made almost exclusively to go through data collections like the array. But not everything is flowers with the foreach you will only be able to go through the elements in a single direction, that is, increasing from the beginning to the end of the collection, with the for you have the pliability from start to finish and vice versa. In short you will use the for or the foreach depending on the application not aiming only the 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';


?>

inserir a descrição da imagem aqui

I hope I’ve helped.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.