开发者

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 t开发者_Python百科o 0?


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.


You lack brackets in your ternary operator, see the example in the operator precedence:

$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

Your example:

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

So depending on your $_POST and $_GET you might even get an "invalid index" PHP warning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜