1st off I’m new to PHP. I have been using for loop,while loop,foreach loop in scripts. I wonder
- which one is better for performance?
- what’s the criteria to select a loop?
- which should be used when we loop inside another loop?
the code which I’m stuck with wondering which loop to be used.
for($i=0;$i<count($all);$i++)
{
//do some tasks here
for($j=0;$j<count($rows);$j++)
{
//do some other tasks here
}
}
It’s pretty obvious that I can write the above code using while. Hope someone will help me out to figure out which loop should be better to be used.
It doesn’t matter.
If you just need to walk through all the elements of an object or array, use
foreach. Cases where you needforincludeforeachis much more convenient because it doesn’t require you to set up the counting, and can work its way through any kind of member – be it object properties or associative array elements (which aforwon’t catch). It’s usually best for readability.Both are fine; in your demo case,
foreachis the simplest way to go.