Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach loop vs while loop results

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...?

like image 908
Tomazi Avatar asked Oct 10 '14 13:10

Tomazi


People also ask

Which is faster foreach or while loop?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

What is difference between while and foreach?

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.

Which is better for loop or foreach?

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.

Is foreach more efficient?

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.


1 Answers

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.

like image 71
ItalyPaleAle Avatar answered Oct 05 '22 23:10

ItalyPaleAle