Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected cast to boolean?

Given this input: http://example.com/item.php?room=248&supply_id=18823, the following 2 blocks ought to produce the same result. Why don't they? What am I missing other than 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 do the check and the assignment in one step, $id ends up equal to 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'm using:

function validkey($value){
    if(is_scalar($value)){
        $value=(int)$value;
        return ($value>0) ? $value : false;
    }
    return false;
}
like image 672
dnagirl Avatar asked Dec 16 '22 17:12

dnagirl


1 Answers

You should use parentheses:

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

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

like image 56
meze Avatar answered Dec 19 '22 05:12

meze