©
本文档使用
php.cn手册 发布
这是最简单的类型。 boolean 表达了真值,可以为 TRUE
或 FALSE
。
要指定一个布尔值,使用关键字 TRUE
或 FALSE
。两个都不区分大小写。
<?php
$foo = True ; // assign the value TRUE to $foo
?>
通常运算符所返回的 boolean 值结果会被传递给控制流程。
<?php
// == 是一个操作符,它检测两个变量是否相等,并返回一个布尔值
if ( $action == "show_version" ) {
echo "The version is 1.23" ;
}
// 这样做是不必要的...
if ( $show_separators == TRUE ) {
echo "<hr>\n" ;
}
// ...因为可以使用下面这种简单的方式:
if ( $show_separators ) {
echo "<hr>\n" ;
}
?>
要明确地将一个值转换成 boolean ,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制结构需要一个 boolean 参数时,该值会被自动转换。
参见类型转换的判别。
当转换为 boolean 时,以下值被认为是 FALSE
:
FALSE
本身
所有其它值都被认为是 TRUE
(包括任何资源)。
-1 和其它非零值(不论正负)一样,被认为是 TRUE
!
<?php
var_dump ((bool) "" ); // bool(false)
var_dump ((bool) 1 ); // bool(true)
var_dump ((bool) - 2 ); // bool(true)
var_dump ((bool) "foo" ); // bool(true)
var_dump ((bool) 2.3e5 ); // bool(true)
var_dump ((bool) array( 12 )); // bool(true)
var_dump ((bool) array()); // bool(false)
var_dump ((bool) "false" ); // bool(true)
?>
[#1] marklgr [2015-10-21 14:22:25]
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.
[#2] emanuelemicciulla[at]gmail[dot]com [2014-11-13 18:08:05]
A lot of people apparently looking for this:
<?php
$strictBool = filter_var($stringBool, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if($boolFanOvr === null) { };
?>
it's TRUE for "true" "True" "TRUE" "Yes" "1" and so on.
FALSE for "false" "0" "no" and so on.
it's NULL if string doesn't represent a valid boolean.
[#3] den [2014-01-17 09:18:22]
Casting bools to string is not working as maybe expected:
echo 'true as string gives [' . (string) true . "] not [true].\n";
echo 'false as string gives [' . (string) false . "] not [false].\n";
Output:
true as string gives [1] not [true].
false as string gives [] not [false].
This helps around that behavior:
true ? 'true' : 'false'
[#4] Fred Koschara [2013-05-15 17:38:11]
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:
<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
?>
Is $z TRUE or FALSE?
In this case, $z will be FALSE because the above code is equivalent to
<?php ($z=$y) OR $x ?>
rather than
<?php $z=($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:
<?php
$x=TRUE;
$y=FALSE;
$z=$y || $x;
?>
$z will be TRUE, as expected, because the || operator has higher precedence than assignment: The code is equivalent to $z=($y OR $x).
This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used.
[#5] geza at turigeza dot com [2013-03-26 18:14:31]
// someKey is a boolean true
$array = array('someKey'=>true);
// in the following 'false' string gets converted to a boolean true
if($array['someKey'] != 'false')
echo 'The value of someKey is '.$array['someKey'];
As a result the above will output nothing :)
if($array['someKey'] == 'false')
echo 'The value of someKey is '.$array['someKey'];
And the above will output
The value of someKey is 1
In short true == 'false' is true.
[#6] Ivan Stojmenovic [2013-03-13 17:48:02]
This is simple example how can convert String to Boolean.
<?php
// Convert string to boolean
function convertStr($str) {
return is_string($str) ? (bool) $str : (string) $str;
}
// Example
$foo = convertStr('apple');
var_dump($foo); // Return TRUE
$foo = convertStr(1); // Return STRING
var_dump($foo);
?>
[#7] pablo at loop-sistemas dot com dot ar [2011-08-09 12:22:17]
altough it may be obvious to some, special value NaN evaluates to true, as it not in the false list
the same goes with INF and -INF
[#8] oscar at oveas dot com [2010-12-01 03:17:59]
Dunno if someone else posted this solution already, but if not, here's a useful and function to convert strings to strict booleans.
Note this one only checks for string and defaults to the PHP (boolean) cast where e.g. -1 returns true, but you easily add some elseifs for other datatypes.
<?php
function toStrictBoolean ($_val, $_trueValues = array('yes', 'y', 'true'), $_forceLowercase = true)
{
if (is_string($_val)) {
return (in_array(
($_forceLowercase?strtolower($_val):$_val)
, $_trueValues)
);
} else {
return (boolean) $_val;
}
}
?>
[#9] ledadu at gmail dot com [2010-10-27 08:56:20]
Function to sort array by elements and count of element (before php 5.3) (not use Lambda Functions, and Closures)
<?php
//-----------------------------
function arraySortByElements($array2sort,$sortField,$order,$iscount=false) {
$functionString='
if ('.($iscount?'true':'false').'){
if(count($a["'.$sortField.'"]) > count($b["'.$sortField.'"])) return 1*'.$order.';
if(count($a["'.$sortField.'"]) < count($b["'.$sortField.'"])) return -1*'.$order.';
}else{
if($a["'.$sortField.'"] > $b["'.$sortField.'"]) return 1*'.$order.';
if($a["'.$sortField.'"] < $b["'.$sortField.'"]) return -1*'.$order.';
}
return 0;';
usort($array2sort, create_function('$a,$b',$functionString));
return $array2sort;
}
//-----------------------------
//init Array for testing :
$testArray = array(
array('name' => 'Lenny', 'note' => 5, 'listId' => array(654,987,32165)),
array('name' => 'Olivier', 'note' =>3, 'listId' => array(2)),
array('name' => 'Gregory', 'note' => 1, 'listId' => array(45,58)),
array('name' => 'Clement', 'note' => 2, 'listId' => array(584,587,741,14781,147))
);
//sorted Arrays :
$testArrayByNameASC = arraySortByElements($testArray,'name',1);
$testArrayByNoteDESC = arraySortByElements($testArray,'note',-1);
$testArrayByCountlistIdDESC = arraySortByElements($testArray,'listId',-1,true);
?>
[#10] fyrye at torntech dot com [2010-06-14 04:39:55]
Since I haven't seen it posted.
Here is a function that you can use if you have a need to force strict boolean values.
Hopefully this will save someone some time from searching for similar.
<?php
function strictBool($val=false){
return is_integer($val)?false:$val == 1;
}
?>
Simply put, it verifies that the value passed is (bool)true otherwise it's false.
Examples:
__________________________________
<?php
$myBool = strictBool(true);
var_dump($myBool);
//returns (bool)true
$myar = array(0 => true);
$myBool = strictBool($myar[0]);
var_dump($myBool);
//returns (bool)true
$myBool = strictBool("hello");
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(false);
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(array(0 => "hello"));
var_dump($myBool);
//returns (bool)false
$myBool = strictBool(1);
var_dump($myBool);
//returns (bool)false
$myBool = strictBool();
var_dump($myBool);
//returns (bool)false
?>
[#11] mercusmaximus at yahoo dot com [2010-02-06 13:50:55]
Note that the comparison: (false == 0) evaluates to true and so will any value you set to false as well (without casting).
[#12] Symbol [2009-04-11 13:35:25]
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)
[#13] ashafer01 at gmail dot com [2009-02-25 19:59:53]
A note when working with PostgreSQL - if you select a boolean field from the database, it returns 't' or 'f'. If you directly evaluate a variable storing a boolean from a PostgreSQL database, it will always return true.
For example...
<?php
$x = pg_query("SELECT someBool FROM atable");
$x = pg_fetch_array($x);
$x = $x['someBool'];
if ($x) echo "true";
else echo "false";
?>
...ALWAYS outputs true
[#14] admin at eexit dot fr [2008-11-04 12:27:04]
Beware of certain control behavior with boolean and non boolean values :
<?php
// Consider that the 0 could by any parameters including itself
var_dump(0 == 1); // false
var_dump(0 == (bool)'all'); // false
var_dump(0 == 'all'); // TRUE, take care
var_dump(0 === 'all'); // false
// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)0 == 'all'); // false
?>
[#15] wbcarts at juno dot com [2008-10-06 11:59:43]
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.
<?php
function boolNumber($bValue = false) { // returns integer
return ($bValue ? 1 : 0);
}
function boolString($bValue = false) { // returns string
return ($bValue ? 'true' : 'false');
}
$a = true; // boolean value
echo 'boolean $a AS string = ' . boolString($a) . '<br>'; // boolean as a string
echo 'boolean $a AS number = ' . boolNumber($a) . '<br>'; // boolean as a number
echo '<br>';
$b = (45 > 90); // boolean value
echo 'boolean $b AS string = ' . boolString($b) . '<br>'; // boolean as a string
echo 'boolean $b AS number = ' . boolNumber($b) . '<br>'; // boolean as a number
echo '<br>';
$c = boolNumber(10 > 8) + boolNumber(!(5 > 10)); // adding booleans
echo 'integer $c = ' . $c .'<br>';
?>
Results in the following being printed...
boolean $a AS string = true
boolean $a AS number = 1
boolean $b AS string = false
boolean $b AS number = 0
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.
[#16] Wackzingo [2008-01-27 06:39:43]
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.
<?php
$var1 = TRUE;
$var2 = FALSE;
echo $var1; // Will display the number 1
echo $var2; //Will display nothing
echo (int)$var2; //This will display the number 0 for false.
?>
[#17] Steve [2008-01-15 15:00:21]
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.
[#18] Anonymous [2008-01-06 07:05:52]
Note that the symbolic constants TRUE and FALSE are treated differently. I was told that this is a feature, not a bug.
echo false ;
echo (false) ;
echo false+false ;
echo (false+false) ;
echo intval(false) ;
echo '"'.false.'"' ;
echo true ;
echo (true) ;
echo true+true ;
echo (true+true) ;
echo intval(true) ;
echo '"'.true.'"' ;
should produce
00000"0"11221"1"
but instead produces
000""11221"1"
In other words, the only way to output the underlying zero or use it in a string is to use 'false+false' or pass it through intval(). No such tricks are required to get at the 1 that underlies true.
The whole idea of symbolic constants is that the underlying value *always* replaces them during translation, and thus anywhere you would otherwise have to use some obscure "magic number" such as 191, you can use a symbolic constant that makes sense, such as TOTAL_NATIONS.
Exactly what php gets out of breaking this rule was not explained to me.
[#19] artktec at gmail dot com [2007-09-27 09:37:28]
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:
<?php
$t = !0; // This will === true;
$f = !1; // This will === false;
?>
And non-integers are casted as if to bool, then NOT.
Example:
<?php
$a = !array(); // This will === true;
$a = !array('a'); // This will === false;
$s = !""; // This will === true;
$s = !"hello"; // This will === false;
?>
To cast as if using a (bool) you can NOT the NOT with "!!" (double '!'), then you are casting to the correct (bool).
Example:
<?php
$a = !!array(); // This will === false; (as expected)
$status = (!!$array ? 'complete' : 'incomplete');
$s = !!"testing"; // This will === true; (as expected)
?>
[#20] terminatorul at gmail dot com [2007-04-29 14:21:42]
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.