Wrong or right? While loops

Heya guys, now ive never done this method before, and I just tried it to see if it would work, and it works like a dream.

Usually people tend to do this.

$tags = array(); while($row = $statement->FetchObject()) { $tags[] = $row; } 

but will it be faster or just less code if I do it this way.

 $tags = array(); while($tags[] = $statement->FetchObject()){} 

It’s just interesting that everyone


Update:

I understand that Cleaner code is much better than Less code, but since I never used this method before it was just a curiosity for the pros and cons.

+4
source share
5 answers

A common problem is that to exit the while , the result must be false. In your second example, this means that at the end of your array there will be a β€œfalse” value (which is most likely not what you want).

This is not a problem for the traditional approach, since the value "false" is assigned to $row and is never applied to the array.

As far as performance or readability is concerned, they are not a problem since the code does not do what you want.

+15
source

And if you are using a database class, just use the predefined method for this. PDO, for example, has fetchAll : $statement->fetchAll(PDO::FETCH_OBJ) .

+3
source

I believe the former is much more readable and easy to understand, and I'm sure the performance difference between them is unbearable.

I am all for 1).

+1
source

You can even skip brackets:

 $tags = array(); while ($tags[] = $stmt->fetchObject()); 

This code, of course, is slightly shorter than the more complex form:

 $tags = array(); while ($tag = $stmt->fetchObject()) { $tags[] = $tag; } 

However, which one is easier to read? You could say that both of them are completely obvious, and in fact I would agree with you. But which one is easier to maintain? To add a new statement like $tag->doSth(); into a shorter form, you need to completely rewrite it. In the latter, you simply add this statement.

+1
source

Of course, if FetchObject() changes its return value accordingly each time it calls;)

0
source

All Articles