Unexpected cast in boolean?

Given this input: http://example.com/item.php?room=248&supply_id=18823 , the following 2 blocks should give the same result. Why not? What will I miss besides coffee?

This block gives the expected values:

if (isset($_GET['supply_id']) && isset($_GET['room'])) {
    $id=validkey($_GET['supply_id']); //18823
    $room=validkey($_GET['room']); //248
    $arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248
}

But if I check and assignment in one step, $ id ends with 1 instead of 18823. Why?

if (isset($_GET['supply_id']) && isset($_GET['room'])) {
    if($id=validkey($_GET['supply_id']) && $room=validkey($_GET['room'])) 
        $arr=array('s'=>$id",'r'=>$room); //s=>1, r=>248
}

This is the function I use:

function validkey($value){
    if(is_scalar($value)){
        $value=(int)$value;
        return ($value>0) ? $value : false;
    }
    return false;
}
+4
source share
3 answers

You should use parentheses:

if(($id=validkey($_GET['supply_id'])) && ($room=validkey($_GET['room']))) 

Otherwise, the result is validkey($_GET['supply_id']) && $room=validkey($_GET['room'])assigned to the variable $id, because the operator &&has a higher priority than=

+7
source

&& , =.

, if ($id = (validkey($_GET['supply_id']) && $room = validkey($_GET['room'])))

- > $foo = $bar IF.

+3

You seem to have a small mistake in your second example - a stray double quote after $ id. In addition, your second approach is generally not approved (assigning variables in the if construct), since it makes code execution much more difficult. Clearer will be as follows:

if (isset($_GET['supply_id']) && isset($_GET['room'])) {     
    $id=validkey($_GET['supply_id']); //18823     
    $room=validkey($_GET['room']); //248

    if($id && $room) {     
        $arr=array('s'=>$id,'r'=>$room); //s=>18823, r=>248 
    }
} 
+2
source

All Articles