thank_you
thank_you

Reputation: 11107

While Loops and Multiple Conditions

Is it possible to write multiple conditions in a while loop? If not, what is an alternative? I tried it and was returned with an error relating the line of code that sets up the conditions for the while loop. Here is an example of what I mean.

$s = 1;

while ($result_row = mysql_fetch_assoc($query) && $s < 5)
{
echo $result_row['id'];
$s++;
}

Upvotes: 11

Views: 56548

Answers (4)

Mark Byers
Mark Byers

Reputation: 838116

That is possible, but because = has lower precedence than && you need parentheses to ensure that your statement is interpreted correctly:

while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))

The parentheses around $s < 5 are not required here, but I've included them for clarity.

However it would be easier just to modify your query to only return 5 rows, by adding LIMIT 5.

SELECT ...
FROM yourtable
ORDER BY ...
LIMIT 5

Upvotes: 34

Mike Christensen
Mike Christensen

Reputation: 91598

The value of $result_row is probably being set to the Boolean condition of whether mysql_fetch_assoc($query) returns something true-ish and $s is less than 5. So trying to read $result_row as a dictionary no longer works.

You can use parenthesis to specify exactly how things get parsed:

while (($result_row = mysql_fetch_assoc($query)) && ($s < 5))

This way, $result_row gets set to mysql_fetch_assoc($query), which is what you want, and the loop continues as long as the logical value of that assignment returns something true-ish, as well as s is less than 5.

Upvotes: 0

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

while i see nothing wrong in that. the other way round is to do something like this.

$s = 1;
while ($result_row = mysql_fetch_assoc($query))
{
    if($s < 5) {
        //enter the condition
    }
    $s++;
}

Upvotes: 0

JoeTomato
JoeTomato

Reputation: 316

You could try:

$s=1
while ($result_row = mysql_fetch_assoc($query))
{
    echo $result_row['id'];
    $s++;
    if($s>5){
        break;
    }
}

http://php.net/manual/en/control-structures.break.php

Upvotes: 1

Related Questions