开发者

PHP snippet not working as I expected

I have this variable: $logged_in_person_rsvp - its value = -1

Then I run this code:

$yes_checked = ($logged_in_person_rsvp===1) ? "checked" : "";
$maybe_checked = ($logged_in_person_rsvp===-1) ? "checked" : "";
$no_checked = ($logged_in_person_rsvp===0) ? "checked" : "";

echo '开发者_Go百科<p>logged_in_person_rsvp: '.$maybe_checked.'</p>';

And I get output as nothing. But I was expecting the output to be -1

Anyone understand why? This is weird syntax I inherited :)


Try using two equals signs like "==" instead of 3 and see if that makes a difference. If so, your strict comparison is probably messing up your intended result.


you have echoed $maybe_checked

and $maybe_checked would be either "checked" or "", how would you expect it to be -1?

echoing $logged_in_person_rsvp should output -1

===================

Respond to your comment:

then try use operator == instead

=== is strict comparison between two variables


The value of each one of these variables will be either "checked" or "", depending on the result of the operation in the brackets.

($logged_in_person_rsvp===-1) ? "checked" : "";

basically, what this does is check whether $logged_in_person_rsvp===-1 is true or false. If it is true, the variable will be assigned "checked", if it is false, the variable will be assigned "".


The ternary syntax is often confusing for newcomers. This is an alternative way using an array-map to express your code:

$checked = array(FALSE => "", TRUE => "checked");

$yes_checked =   $checked[($logged_in_person_rsvp===1)];
$maybe_checked = $checked[($logged_in_person_rsvp===-1)];
$no_checked =    $checked[($logged_in_person_rsvp===0)];

echo '<p>logged_in_person_rsvp: '.$maybe_checked.'</p>';

The === is just a strict version of the normal equal == operator.


Ternary operations should be enclosed in parentheses.

$maybe_checked = ($logged_in_person_rsvp===-1 ? "checked" : "");

That should do the trick.

EDIT: Also, make sure that your $logged_in_person_rsvp is -1 the integer, not '-1' the string. Or try using == instead of ===.


Have you tried var_dump($logged_in_person_rsvp); (or inspecting the value in xdebug, or firephp, or your choice of debugger) to determine what type $logged_in_person_rsvp is?

Using the snippet you provided, if I set:

$logged_in_person_rsvp = -1;

everything works fine, and I get <p>logged_in_person_rsvp: checked</p> but if I set:

$logged_in_person_rsvp = "-1";

then I get <p>logged_in_person_rsvp: </p>

As it has been pointed out by others, == will try to cast the two sides of the comparison to the same type, but === will check type as well and fail if one is a string and one is an int/float.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜