How do i change a Foreach loop into a For loop?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Personally when needing a for loop I tend to use a range...

Code: Select all

foreach (range(1,10) as $num) {
  echo($num.'<br />');
}
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Robert Plank wrote:
That's odd.. I just made a quick test suite
I guess it would be more fair if our code actually checked an array instead of counting up numbers.

results:

Code: Select all

test_ForeachWithIndice() 79.1614859104 seconds
test_ForeachWithoutIndice() 69.2696409225 seconds
test_For() 71.0619039536 seconds
Sorry it's taken me so long to reply. I just ran your test suite and these were my results.

Code: Select all

test_ForeachWithIndice() 75.1973428726 seconds
test_ForeachWithoutIndice() 70.8360300064 seconds
test_For() 66.339318037 seconds
I can't really explain why your for() is slower than a foreach(). From all the results I've ever processed and debates seen for() was always the fastest.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

CoderGoblin wrote:Personally when needing a for loop I tend to use a range...

Code: Select all

foreach (range(1,10) as $num) {
  echo($num.'<br />');
}
Seems like a waste of rescources, very minimal although but still not ideal in my books. You can hammer a nail with a sludge hammer -- or you can use the right tool for the job.
Post Reply