16

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

boomoto
  • 311
  • 1
  • 9
Tomazi
  • 787
  • 3
  • 11
  • 30
  • Not sure, I always use a while loop for database selects – boomoto Oct 10 '14 at 13:46
  • 1
    I don't think this question is a duplicate of the one posted, though. – ItalyPaleAle Oct 10 '14 at 13:49
  • @Qualcuno Actually, you're kind of right. More like a duplicate of http://stackoverflow.com/questions/3304885/whilelistkey-value-eacharray-vs-foreacharray-as-key-value which you mention `(Traversable)` in your answer. If OP wants it reopened, he/she can contest it. – Funk Forty Niner Oct 10 '14 at 13:52
  • @Fred-ii- it's more similar to that, but I think it still has some uniqueness because it's talking about a specific class. – ItalyPaleAle Oct 10 '14 at 13:53
  • You can iterate over every collection using `while`, but it does not mean you should do it. I would always prefer `foreach` for collections and `while` loops for something else – Royal Bg Oct 10 '14 at 13:54
  • @Qualcuno There is actually a difference between both, one will fetch results till nothing else is found, while the other will do it for as long as the loop lasts. That's the duplicate I was searching for, which has been asked before. I will reopen the question. If it gets closed again after that, I'll have no control over it. – Funk Forty Niner Oct 10 '14 at 13:54
  • This question should be something like "Foreach loop vs while loop on fetching mysqli results". The essential point here is the behaviour of mysqli (along with while and foreach) which is barely mentioned in the question – hlscalon Oct 10 '14 at 13:55
  • @Fred-ii- true, but "the loop lasts" until there aren't any more results, if I'm not wrong! In practice, I'd say the behaviour is basically equivalent. – ItalyPaleAle Oct 10 '14 at 13:57
  • @Qualcuno True. I'm going to find the actual post for it. Best to dot the `i`'s and bar the `T`'s ;) **Edit:** Here's one http://stackoverflow.com/questions/2590792/what-are-the-difference-between-for-loop-for-each-loop-in-php which would have been more appropriate as the dupe. – Funk Forty Niner Oct 10 '14 at 13:58
  • 1
    wow guys my question is the behaviour of these loops in the given situation...situation the the key ward here and my question might be simillar to others but is unique in a way. But thank you guys for trying to answer my question :) – Tomazi Oct 10 '14 at 14:01
  • @Tomazi Which is why I reopened the question. I hope the answer/comments have served you well. – Funk Forty Niner Oct 10 '14 at 14:03
  • :) thank you @Fred-ii- yep read some usefully suggestions. – Tomazi Oct 10 '14 at 14:07
  • Definitely not a dup of the other questions: One code snippet explicitly calls `mysqli_fetch_assoc`, the other does not. It isn't inherently obvious that the `foreach` performs `fetch_assoc`, hence this question is important, independently of the looping constructs. – ToolmakerSteve Mar 10 '20 at 00:29

2 Answers2

4

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.

ItalyPaleAle
  • 7,185
  • 6
  • 42
  • 69
  • Philosophically, it seems cleaner to iterate over list elements then to test whether we're at the end of the list and then iterate to the next element, so I agree. – erik258 Dec 30 '15 at 22:54
-1

I found this:

for vs foreach vs while which is faster for iterating through arrays in php

the answer states that a difference in speed is so minimal that hardly matters which you use.

I like using foreach loops to iterate over returned information because I have access to the keys and values, which can be handy depending on the needed use.

$returned = array(array("userName" => "Tim"),array("userName" => "Bob"), array("userName" => "Guy"));

foreach($returned as $L1)
{
  foreach($L1 as $L2 => $val)
  {
      if($L2 === "userName")
      {

         echo 'Hello: ' . $val . "<br />";

      }

  }

}

I guess it depends on what values you need, how much control you need, and where you need it.

ToolmakerSteve
  • 18,547
  • 14
  • 94
  • 196
user2296112
  • 146
  • 1
  • 10
  • 1
    how that differs from `while` and `each` – Royal Bg Oct 10 '14 at 14:44
  • I was just stating what I like to use and offering what another post offered on speediness. Don't have a cow, lol. – user2296112 Oct 12 '14 at 02:48
  • At first I thought the link was useful, but the timing results probably do not apply to this situation: $result isn't an array, it is an object that understands `mysqli_fetch_assoc()`. Timing is probably dominated by that `fetch_assoc` per iteration, not by any loop overhead. – ToolmakerSteve Mar 10 '20 at 00:20