开发者

Wrong or Right ? While loops

开发者 https://www.devze.com 2023-01-12 20:15 出处:网络
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.

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()){}
开发者_如何学C

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.


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.


And if you're database class allows it, simply use the predefined method for this purpose. PDO for example has fetchAll: $statement->fetchAll(PDO::FETCH_OBJ).


I find the former much more readable and easy to grasp, and I'm sure any performance difference between the two is negligeable.

I'm all for 1).


You could even skip the brackets:

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

That code certainly is a bit shorter that it's more verbose form:

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

However which one is easier to read? You could say both are quite obvious and actually I would agree with you. But which one is easier in general maintenance? To add a new statement like $tag->doSth(); in shorter form you have to completely rewrite it. In the last one you just add that statement.


Sure, as long as FetchObject() changes its return value appropriately each time it's called ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号