Domanda

When I echo a PHP Boolean value in HTML, whether inside a tag or outside, the PHP code returned seems to be an empty string for false and "1" for true. This happens with the Boolean objects, and variables which return Boolean values, but not the strings "true" and "false". For example, in the following code,

<div id="<?php echo true; ?>"><?php echo true; ?></div>

<div id="<?php echo false; ?>"><?php echo false; ?></div>

the first div will have an ID of "true" and will have "true" as its text, while the second div will have an ID of "false" and will have "false" as its content. I have tested this in Google Chrome 34 and Firefox 29 Beta (IE11 won't load the page). I used Firebug, Google Chrome's Web Developer Tools, and Firebug Lite to see what the browser won't show. What's going on here?

È stato utile?

Soluzione

echo is basically converting the boolean value to a string then printing it. The issue is that false, when stringified, is the empty string "", while trueis a non-empty string '1'.

Why is this odd behavior taking place? The creators of PHP want equality to remain transitive when converting types.

A common design question is: what strings are truthy (succeed when compared to true) and what strings are falsy (succeed when compared to false). Many languages consider the empty string "" to by falsy and any non-empty string to be truthy.

From this link, you can see that:

(bool) "" == false
(bool) "1" == true
(bool) "0" == true  // this is the important part
(bool) "true" == true
(bool) "false" == true // also of note

Its nice to have ((string) false) == false and ((bool) ((string) false)) == false.

Other languages, such as JavaScript, break transitivity for ==. Many consider this to be a "bad part" of JavaScript.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top