手册学习 Boolean 布尔类型

当转换为 boolean 时,以下值被认为是 FALSE

所有其它值都被认为是 TRUE(包括任何资源)。

Warning

-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.

<?php
$x=TRUE;
$y=FALSE;
$z=$y OR $x;
?>

$z 为FALSE  因为运算符优先级大于OR  $z=$y OR $x; 为($z=$y) OR $x  非 $z=($yOR $x)

<?php
$x=TRUE;
$y=FALSE;
$z=$y || $x;
?>

$z 为TRUE ||优先级大于运算符 $z=$y || $x 为$z=($yOR $x)

 

2.

<?php
// Consider that the 0 could by any parameters including itself

//考虑到0可以通过任何参数,包括自己
var_dump(== 1); // false
var_dump(== (bool)'all'); // false
var_dump(== 'all'); // TRUE, take care
var_dump(=== 'all'); // false

// To avoid this behavior, you need to cast your parameter as string like that :
var_dump((string)== 'all'); // false

 

3

// 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.

?>

 

4.

echo false ;  //空
echo (false) ; //空
echo false+false ; //0
echo (false+false) ;  //0
echo intval(false) ; //0
echo '"'.false.'"' ; // ""

echo true ; //1
echo (true) ; //1
echo true+true ;  //2
echo (true+true) ; //2
echo intval(true) ; /1
echo '"'.true.'"' ; /"1"

 

5

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].

 

转载于:https://www.cnblogs.com/phperhuzi/p/4807059.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值