Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this loop return 1 when using && instead of 'and'?

Tags:

php

logic

gearman

Riddle me this... in the while($row = mysql_fetch_assoc($result) and $runningOK) loop, if the PHP && operator is used in place of the and then mysql_fetch_assoc fails terribly and returns just the number 1 when running.

I've tried mysql_fetch_array() and in place and I still have the 1 problem. It is when, and only when, I replace the && with an and like the current while statement that the correct rows are returned.

I had placed debug statements before, inside, and after to insure this. I would like to know if this is a PHP quirk or something I couldn't account for.

// Query
$selectQuery = "SELECT * FROM jobs_cache LIMIT 20";
// Run the Selection Query.
$result = mysql_query($selectQuery)
    or die('Query Failed: '.mysql_error());

// Loop through results.
$runningOK = TRUE;
$resubmitList = array();

while($row = mysql_fetch_assoc($result) and $runningOK)
{
    // Resubmit The Job
    try
    {
        $client->addTaskBackground($row['function_name'],$row['job_data']);
        $resubmitList[] = (string)$row['job_cache_id'];
    }
    catch(Exception $e)
    {
        echo "Error adding task for job id: " . $row['job_cache_id'];
        $runningOK = FALSE;
    }
}
like image 607
Urda Avatar asked Apr 02 '26 03:04

Urda


1 Answers

It's due to operator precedence. See the manual for details... here's the relevant part.

// "&&" has a greater precedence than "and"

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))

$g = true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)

$h = true and false;

var_dump($g, $h);

bool(false)
bool(true)

So, with the &&, the result of the expression is assigned to true, which evaluates to 1. With and, it evaluates to the result of the mysql function - more what you want, I reckon.

By the way, you could also use break to eliminate the need for the $runningOK variable. To do so, remove and $runningOK from the while condition and change $runningOK = FALSE; to break; and it will end the loop if the catch block is triggered.

like image 196
JAL Avatar answered Apr 03 '26 16:04

JAL