Search code examples
phploose-typing

Very Unusual PHP Behaviour


for the code below I get a page that does print task and then exit even though the value of task is zero.

$task = (isset($_POST['task']))?$_POST['task'] :(isset($_GET['task']))?$_GET['task']:0; 
if($task == "delete") {
    echo $task;
    exit(); 
}

output:

0

however if I change the first line to:

$task = (isset($_POST['task'])) ? $_POST['task'] :(isset($_GET['task'])) ? $_GET['task'] : NULL;    

it will work normally, so why is it that the value of a the string 'delete' is equal to 0?


Solution

  • any string that can't be converted to a number is automatically converted to 0; so "delete" is 0 when comparing to a number.

    you can compare using identity operator to check types as well

    if($task === "delete") {
        echo $task;
        exit(); 
    }
    

    This will ensure that type is checked and return false as a result.