Hướng dẫn dùng destructing definition trong PHP
This is the simplest type. A bool expresses a truth value. It can be either true or false. SyntaxTo specify a bool literal, use the constants true or false. Both are case-insensitive. $foo = True; // assign the value TRUE to $foo Typically, the result of an operator which returns a bool value is passed on to a control structure. // == is an operator which tests Converting to booleanTo explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument. See also Type Juggling. When converting to bool, the following values are considered false:
Every other value is considered true (including any resource and NAN). Warning -1 is considered true, like any other non-zero (whether negative or positive) number! var_dump((bool) ""); // bool(false) Fred Koschara ¶ 9 years ago Ah, yes, booleans - bit values that are either set (TRUE) or not set (FALSE). Now that we have 64 bit compilers using an int variable for booleans, there is *one* value which is FALSE (zero) and 2**64-1 values that are TRUE (everything else). It appears there's a lot more truth in this universe, but false can trump anything that's true... PHP's handling of strings as booleans is *almost* correct - an empty string is FALSE, and a non-empty string is TRUE - with one exception: A string containing a single zero is considered FALSE. Why? If *any* non-empty strings are going to be considered FALSE, why *only* a single zero? Why not "FALSE" (preferably case insensitive), or "0.0" (with how many decimal places), or "NO" (again, case insensitive), or ... ? The *correct* design would have been that *any* non-empty string is TRUE - period, end of story. Instead, there's another GOTCHA for the less-than-completely-experienced programmer to watch out for, and fixing the language's design error at this late date would undoubtedly break so many things that the correction is completely out of the question. Speaking of GOTCHAs, consider this code sequence: In this case, $z will be FALSE because the above code is equivalent to ($z=$y) OR $x ?> rather than =($y OR $x) ?> as might be expected - because the OR operator has lower precedence than assignment operators. On the other hand, after this code sequence: This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used. Mark Simon ¶ 5 years ago Note for JavaScript developers: In PHP, an empty array evaluates to false, while in JavaScript an empty array evaluates to true. In PHP, you can test an empty array as if(!$stuff) …; ?> which won’t work in JavaScript where you need to test the array length. This is because in JavaScript, an array is an object, and, while it may not have any elements, it is still regarded as something. Just a trap for young players who routinely work in both langauges. admin at eexit dot fr ¶ 13 years ago Beware of certain control behavior with boolean and non boolean values : //
Consider that the 0 could by any parameters including itself // To avoid this behavior, you need to cast your parameter as string like that : var_dump((string)0 == 'all'); // false?> goran77 at fastmail dot fm ¶ 6 years ago Just something that will probably save time for many new developers: beware of
interpreting FALSE and TRUE as integers. function remove_element($element, $array) So you have to explicitly check for FALSE, otherwise you'll probably loose some elements: //correct terminatorul at gmail dot com ¶ 15 years ago Beware that "0.00" converts to boolean TRUE ! You may get such a string from your database, if you have columns of type DECIMAL or CURRENCY. In such cases you have to explicitly check if the value is != 0 or to explicitly convert the value to int also, not only to boolean. Steve ¶ 14 years ago PHP does not break any rules with the values of true and false. The value false is not a constant for the number 0, it is a boolean value that indicates false. The value true is also not a constant for 1, it is a special boolean value that indicates true. It just happens to cast to integer 1 when you print it or use it in an expression, but it's not the same as a constant for the integer value 1 and you shouldn't use it as one. Notice what it says at the top of the page: A boolean expresses a truth value. It does not say "a boolean expresses a 0 or 1". It's true that symbolic constants are specifically designed to always and only reference their constant value. But booleans are not symbolic constants, they are values. If you're trying to add 2 boolean values you might have other problems in your application. artktec at gmail dot com ¶ 14 years ago Note you can also use the '!' to convert a number to a boolean, as if it was an explicit (bool) cast then NOT. So you can do something like: $t = !0; // This will === true; Example: $a = !array(); // This will === true; Example: $a = !!array(); // This will === false; (as expected) Mark Simon ¶ 5 years ago Note on the OR operator. A previous comment notes the trap you can fall into with this operator. This is about its usefulness. Both OR and || are short-circuited operators, which means they will stop evaluating once they reach a TRUE value. By design, OR is evaluated after assignment (while || is evaluated before assignment). This has the benefit of allowing some simple constructions such as: $stuff=getStuff() or die('oops'); The second allows for an alternative value if a falsy one is regarded as insufficient. The following example $page[email protected]$_GET['page'] or $page[email protected]$_COOKIE['page']
or $page=1; All this presupposes that 0 is also an unacceptable value in the situation. Wackzingo ¶ 14 years ago It is correct that TRUE or FALSE should not be used as constants for the numbers 0 and 1. But there may be times when it might be helpful to see the value of the Boolean as a 1 or 0. Here's how to do it. $var1 = TRUE; echo $var1; // Will display the number 1 echo $var2; //Will display nothing /* To get it to display the number 0 for ?> marklgr ¶ 6 years ago For those wondering why the string "0" is falsy, consider that a good deal of input data is actually string-typed, even when it is semantically numeral. PHP often tries to autoconvert these strings to numeral, as the programmer certainly intended (try 'echo "2"+3'). Consequently, PHP designers decided to treat 0 and "0" similarly, ie. falsy, for consistency and to avoid bugs where the programmer believes he got a true numeral that would happen to be truthy when zero. richie dot hayward at gmail dot com ¶ 6 years ago Actually from a complete noob point of view 0 resulting in false makes sense as many languages as I have been taught consider the value 1 as true and the value 0 as false a simple boolean value. So lets says you think you set a variable to 0 and some how or another through your code this value has implicitly become and string instead of a int or boolean. Should PHP now consider it to evaluate to false. I wouldn't think so but hey I'm a PHP noob so perhaps I'm missing why you would ever want a "0" string to evaluate to true. geza at turigeza dot com ¶ 9 years ago //
someKey is a boolean true // in the following 'false' string gets converted to a boolean true As a result the above will output nothing :) if($array['someKey'] == 'false') And the above will output In short true == 'false' is true. mike652638 at qq dot com ¶ 1 year ago // For those newbies who may also have puzzles as following: $bool_val2 = (bool)false; // But how to print false or 0 (instead of nothing) for the falsy value or condition then ? // Solution1: // Solution2: // Solution3: // Soluton4: // Solution5: fyrye at torntech dot com ¶ 12 years ago Since I haven't seen it posted. Examples: emanuelemicciulla[at]gmail[dot]com ¶ 7 years ago A lot of people apparently looking for this: oscar at oveas dot com ¶ 11 years ago Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans. function toStrictBoolean ($_val, $_trueValues =
array('yes', 'y', 'true'), $_forceLowercase = true) Symbol ¶ 13 years ago Just a side note, doesn't really matters, the reason -1 is true and not false is because boolean type is treated as unsigned, so -1 would be for example, if it's unsigned int32 translate to hex: 0xFFFFFFFF and back to decimal: 4294967295 which is non-zero. there isn't really a "negative boolean". it's a binary thing. :o (since it used to be a bit and then there was only 0 and 1 as an option) Anonymous ¶ 2 years ago What will be the output you think if we add echo and print both at a time.. $a = 5;print print $a; // prints out: 51 inner 'print' prints the value of $a, then // outer 'print' returns the boolean true about print $aecho print $a; // prints out: 51 inner 'print' prints the value of $a, then// outer 'echo' returns the boolean true about print $aecho echo $a; // syntax error.. echo doesn't returnprint echo $a; // syntax error.. echo doesn't return?> mercusmaximus at yahoo dot com ¶ 12 years ago Note that the comparison: (false == 0) evaluates to true and so will any value you set to false as well (without casting). wbcarts at juno dot com ¶ 13 years ago CODING PRACTICE... Much of the confusion about booleans (but not limited to booleans) is the fact that PHP itself automatically makes a type cast or conversion for you, which may NOT be what you want or expect. In most cases, it's better to provide functions that give your program the exact behavior you want. function boolString($bValue = false) { // returns stringreturn ($bValue ? 'true' : 'false'); }$a = true; // boolean value echo 'boolean $a AS string = ' . boolString($a) . ' '; // boolean as a string echo 'boolean $a AS number = ' . boolNumber($a) . ' '; // boolean as a number echo ' ';$b = (45 > 90); // boolean value echo 'boolean $b AS string = ' . boolString($b) . ' '; // boolean as a string echo 'boolean $b AS number = ' . boolNumber($b) . ' '; // boolean as a number echo ' ';$c = boolNumber(10 > 8) + boolNumber(!(5 > 10)); // adding booleans echo 'integer $c = ' . $c .' ';?> Results in the following being printed... boolean $a AS string = true boolean $b AS string = false integer $c = 2 In other words, if we know what we want out of our program, we can create functions to accommodate. Here, we just wanted 'manual control' over numbers and strings, so that PHP doesn't confuse us. sumon dot pdk dot bd at gmail dot com ¶ 2 years ago When compare zero (0) with string it's return true by type jugling. When compare with TRUE with also the same string it's also returning true. echo 0 == 'This is a string'; // 1 |