Re: BP for Looping through an Array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Fri, Oct 28, 2011 at 12:09:24PM -0600, George Langley wrote:
> 	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

If you are certain that your array is consecutively indexed from 
0, you can shave two lines off your code with:

        $allFiles = array("coffee.jpg", "tea.jpg", "milk.jpg");
        foreach ($allFiles as $key => $currFile) {
                doThisWith($currFile);
                doThatWith($key+1);
        }


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux