I have a bit of dilemma, In PHP both foreach loop and while loop seem to do exactly the same thing in this situation:
foreach($execute->result as $item){
echo $item['user_pass'].'<br />';
}
AND
while($row = mysqli_fetch_assoc($execute->result)){
echo $row['user_pass'].'<br />';
}
My question is are there any real differences...? when would be better to use one over another or is it fine to use both....? Does any of these two give you potential greater felxebility...?
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
while − loops through a block of code once, and then repeats the loop as long as a special condition is true. foreach − loops through a block of code for each element in an array.
The FOR loop without length caching and FOREACH work slightly faster on arrays than FOR with length caching. Array. Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays.
The foreach loop is considered to be much better in performance to that of the generic for loop. The foreach loop though iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively.
In this case they're exactly equivalent. The mysqli_result
implements the Traversable
interface (as documented here: http://www.php.net/mysqli_result ) so it can be iterated using a foreach
loop as well.
I suppose that, internally, calling foreach
on a mysqli_result
object performs the calls to mysqli_fetch_assoc
as well.
I don't think it makes any difference to use the first method or the second; however, the first one looks prettier and "more PHP5" to me!
Speaking of flexibility, the first one is certainly more flexible as well, as you can use that code with any object that implements Traversable
and not just mysqli_result
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With