Php 简明教程

PHP - Boolean

在 PHP 中,“bool” 是内置标量数据类型之一。它用于表示真值,可以是 True 或 False。布尔值常量使用 PHP 常量 True 或 False。这些常量不区分大小写,即 true、TRUE 或 True 是同义词。

In PHP, "bool" is one of the built-in scalar data types. It is used to express the truth value, and it can be either True or False. A Boolean literal uses the PHP constants True or False. These constants are case-insensitive, in the sense, true, TRUE or True are synonymous.

你可以如下声明 bool 类型的变量 −

You can declare a variable of bool type as follows −

$a = true;

Example

逻辑运算符 (<, >, ==, != 等)返回布尔值。

Logical operators (<, >, ==, !=, etc.) return Boolean values.

<?php
   $gender="Male";
   var_dump ($gender=="Male");
?>

它将生成以下 output

It will produce the following output

bool(true)

Boolean Values in Control Statements

布尔值用于构造控制语句,如 if, while, forforeach 。这些语句的行为取决于布尔运算符返回的 true/false 值。

Boolean values are used in the construction of control statements such as if, while, for and foreach. The behaviour of these statements depends on the true/false value returned by the Boolean operators.

以下条件语句使用在 if 关键字之前的括号中表达式返回的布尔值 −

The following conditional statement uses the Bool value returned by the expression in the parenthesis in front of the if keyword −

$mark=60;

if ($mark>50)
   echo "pass";
else
   echo "fail";

Converting a Value to Boolean

使用 (bool) 转换运算符将一个值转换为 bool。当一个值在逻辑上下文中使用时,它将自动解释为类型为 bool 的值。

Use the (bool) casting operator to convert a value to bool. When a value is used in a logical context it will be automatically interpreted as a value of type bool.

非零数字被认为是真,只有 0(+0.0 或 -0.0)是假。非空字符串表示真,空字符串 “” 等同于假。同样,一个空数组返回假。

A non-zero number is considered as true, only 0 (+0.0 or -0.0) is false. Non-empty string represents true, empty string "" is equivalent to false. Similarly, an empty array returns false.

Example

请查看以下示例:

Take a look at this following example −

<?php
   $a = 10;
   echo "$a: ";
   var_dump((bool)$a);

   $a = 0;
   echo "$a: ";
   var_dump((bool)$a);

   $a = "Hello";
   echo "$a: ";
   var_dump((bool)$a);

   $a = "";
   echo "$a: ";
   var_dump((bool)$a);

   $a = array();
   echo "$a: ";
   var_dump((bool)$a);
?>

它将生成以下 output

It will produce the following output

10: bool(true)
0: bool(false)
Hello: bool(true)
: bool(false)
Array: bool(false)