Hi all. Am wondering if there is a best practice for looping through an
array, when you need both the item and its position (ie. 1, 2, 3....). The two
ways I know of:
// the for loop tracks the position and you get each item from the array
$allFiles = array("coffee.jpg", "tea.jpg", "milk.jpg");
$numberOfFiles = count($allFiles);
for ($i=1; $i<=$numberOfFiles; $i++) {
$currFile = $allFiles[$i - 1]; // since arrays start with 0
doThisWith($currFile);
doThatWith($i);
}
OR:
// the for loop gets each item and you track the position
$allFiles = array("coffee.jpg", "tea.jpg", "milk.jpg");
$counter = 1;
foreach ($allFiles as $currFile) {
doThisWith($currFile);
doThatWith($counter);
$counter += 1;
}
Both are the same number of lines, but my tests (see code below)
indicate that the foreach loop is twice as fast.
Anyone have a "better" way - faster, more efficient, "cooler", etc.?
(Or see some flaw in my test code below?)
Thanks.
George Langley
-- TEST CODE --
<?php
echo "<h1>Loop Test</h1>";
// create a large array
$theArray = array();
for ($i=1; $i<=1000000; $i++) {
array_push($theArray, $i);
}
$confirmCount = count($theArray);
echo "<h2>An array of $confirmCount items (numbers 1 to $confirmCount) has been
created.</h2>";
echo "<table><tr><td><b>Type of Loop</b></td><td><b>Time Taken to Add
Up</b></td><td><b>addUp Value</b></td></tr>";
for ($x=1; $x<=10; $x++) { // run tests 10x
// the for loop tracks the position and you get each item from the array
$addUp = 0;
$time_start = microtime(true);
$numberOfItems = count($theArray);
for ($i=1; $i<=$numberOfItems; $i++) {
$currItem = $theArray[$i - 1]; // since arrays start with 0
$addUp += $currItem; // give it something to do
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<tr><td>For (Tracks Position):
</td><td>$time</td><td>$addUp</td></tr>";
// the for loop gets each item and you track the position
$addUp = 0;
$time_start = microtime(true);
$counter = 1;
foreach ($theArray as $currItem) {
$addUp += $currItem; // give it something to do
$counter += 1;
}
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "<tr><td>Foreach (Tracks Items):
</td><td>$time</td><td>$addUp</td></tr>";
echo "<tr><td> </td><td> </td><td> </td></tr>";
}
echo "</table>";
?>
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php