布尔类型

本文详细介绍了PHP中布尔值与其他类型值之间的转换规则。包括布尔值如何被转换为字符串、在比较运算中如何与其他类型的值进行自动转换。通过具体示例帮助理解PHP中的类型隐式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要明确地将一个值转换成 boolean,用 (bool) 或者 (boolean) 来强制转换。但是很多情况下不需要用强制转换,因为当运算符,函数或者流程控制结构需要一个 boolean 参数时,该值会被自动转换。

1.布尔值转换为字符串时,true转换为"1",false转换为""空字符串:

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

如果想转换为"true"和"false"可用如下代码:

true ? 'true' : 'false' 

2.当布尔值与非布尔值进行比较时,会将非布尔值转换为布尔值,再进行比较:

// someKey is a boolean true
 $array = array('someKey'=>true);

 // 将'false'转换为布尔值true,因此将什么都不会输出。
 if($array['someKey'] != 'false')
     echo 'The value of someKey is '.$array['someKey'];

  
//将会输出
 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. 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值