Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

but would it be faster or just less code if i done it this way.

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

Just Curious that's all


Update:

I do understand that Cleaner code is much better then Less code, but as I never used this method before it was mere curiosity for pros and cons.

like image 458
RobertPitt Avatar asked Nov 30 '22 10:11

RobertPitt


1 Answers

The general issue is that to exit the while loop, a "false" result needs to be returned. In your second example, that means there will be a "false" value (which is likely not what you want) at the end of your array.

This is not an issue for the traditional approach because the "false" value is given to $row and never applied to the array.

As for performance, or readability, they're non-issues since the code doesn't do what you want it to do.

like image 171
salathe Avatar answered Dec 06 '22 11:12

salathe