To explain previous comments: the reason that the FOR loop runs faster on LARGE arrays if you set its size to an array first (using count() or sizeof() ) is pretty simple. It's because if you use
<?php
for ($i = 0; $i < sizeof($huge_array); $i++)
{
code
}
?>
every time the FOR loop checks its condition (is $i less than sizeof($huge_array) ), it must run the sizeof() function on $huge_array again. This is what causes the extra processing time, which can become significant on larger arrays.
As a side note, this has been thoroughly commented on both correctly and incorrectly in the User Contributed Notes for the count() function. Users Jaik, Wulfson, and Anonymous have summed this particular matter up pretty well in their posts http://www.php.net/manual/en/function.count.php#78741 , http://www.php.net/manual/en/function.count.php#78931 , and http://www.php.net/manual/en/function.count.php#79238 .
sizeof
rrf5000 at psu dot edu
17-Apr-2008 11:54
17-Apr-2008 11:54
Andreas dot Schuhmacher87 at googlemail dot com
14-Apr-2008 03:02
14-Apr-2008 03:02
also you can use for like this (no count() needed)
<?php
for($i = 0, $item = ''; false != ($item = $some_array[$i]); $i++) {
print $item; //index $i of $some_array
//code
}
?>
communiti.ch
10-Apr-2008 10:55
10-Apr-2008 10:55
If your array is "huge"
It is reccomended to set a variable first for this case:
THIS->
$max = sizeof($huge_array);
for($i = 0; $i < $max;$i++)
{
code...
}
IS QUICKER THEN->
for($i = 0; $i < sizeof($huge_array);$i++)
{
code...
}
svanegmond at tinyplanet dot ca
14-Mar-2008 04:12
14-Mar-2008 04:12
For people who use this kind of idiom:
for ($i=0; $i<sizeof($array); $i++) {
...
}
At least in PHP4, you will notice a large performance improvement if you switch to:
$max = sizeof($array);
for ($i=0; $i<$max; $i++) {
...
}
I had an array with a few thousand items in it, each of them a map with 5 key-value pairs, and just for'ing through the array took a second of CPU on a decent machine.