Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While Loops and Multiple Conditions

Tags:

php

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++;
}
like image 633
thank_you Avatar asked Aug 15 '12 20:08

thank_you


People also ask

How to write Python while loops with multiple conditions?

There's one other logical operator that you can use to write Python while loops with multiple conditions, and that's logical not: This operator simply reverses the value of a given boolean expression. In other words, not True will return false, and not False will return true. Let's add a third conditional expression to the code.

What happens when condition is true in a while loop?

As long as the condition is true, the loop body (the indented block that follows) will execute any statements it contains. As soon as the condition evaluates to false, the loop terminates and no more statements will be executed. The simplest while loops in Python are while True and while False:

Can you have multiple if-conditions in a loop?

It is also possible to include several if (or else) conditions inside of a loop. Have a look at the following example code: In the previous R code we nested two if-conditions. However, we may also specify multiple logical conditions within a single if-statement: The output is the same.

How do you combine multiple conditional expressions in a while loop?

Python compares the two values and if the expression evaluates to true, it executes the loop body. However, it's possible to combine multiple conditional expressions in a while loop as well. Python While Loop Multiple Conditions To combine two conditional expressions into one while loop, you'll need to use logical operators.


1 Answers

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
like image 146
Mark Byers Avatar answered Oct 15 '22 16:10

Mark Byers