开发者

Difference between PHP and JS evaluation of variables

Can someone please explain to me why the following javascript code produces an alert with 321 and the PHP code produces 1.

I kno开发者_如何学JAVAw the PHP code evaluates the expression and returns true or false. What I don't know is why in JavaScript it works like a ternary operator. Is it just the way things were implemented in the language?

var something = false;
var somethingelse = (something || 321);
alert(somethingelse); // alerts 321
$var = '123';
$other = ($var || 321);
echo $other; // prints 1

Thanks!


Is it just the way things were implemented in the language?

Yes, JavaScript does it a bit differently. The expression (something || 321) means if something is of a falsy value, a default value of 321 is used instead.

In conditional expressions || acts as a logical OR as usual, but in reality it performs the same coalescing operation. You can test this with the following:

if ((0 || 123) === true)
    alert('0 || 123 evaluates to a Boolean');
else
    alert('0 || 123 does not evaluate to a Boolean');

In PHP the || operator performs a logical OR and gives a Boolean result, nothing else.


I'm actually surprised javascript did not alert 1 or true as well. The syntax you want for js is:

var somethingelse = something || 321;

Wrapping parentheses around something evaluates it as truthy / falsey. For php your are saying:

//$other will equal true if $var is true or 321 is true. 
$other = ($var || 321);

A matching statement in php would look like:

$other = ($var) ? $var : 321;


Just to add on boltClock answer since I can't comment - If you want it be a Boolean value you can parse it to bool like this:

var somthing = !!(somthingelse || 321);


In PHP ($var || 321); is evaluated and assigned to $other.

You can use this in PHP.

($other = $var) || $other = 321;

Update: As BoltClock said in Javascript var somethingelse = (something || 321) seeks to assign a default value to the variable if something is false.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜