php if($variable) 究竟是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6693876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:00:45  来源:igfitidea点击:

How exactly does if($variable) work?

php

提问by Nisto

Possible Duplicate:
Regarding if statements in PHP

可能的重复:
关于 PHP 中的 if 语句

In PHP scripts - what does an if statement like this check for?

在 PHP 脚本中 - 像这样的 if 语句检查什么?

<?php if($variable){ // code to be executed } ?>  

I've seen it used in scripts several times, and now I really want to know what it "looks for". It's not missing anything; it's just a plain variable inside an if statement... I couldn't find any results about this, anywhere, so obviously I'll look stupid posting this.

我已经多次看到它在脚本中使用过,现在我真的很想知道它“寻找”什么。它没有遗漏任何东西;它只是 if 语句中的一个普通变量......我在任何地方都找不到关于此的任何结果,所以显然我会看起来很愚蠢发布这个。

回答by Michael Berkowski

The construct if ($variable)tests to see if $variableevaluates to any "truthy" value. It can be a boolean TRUE, or a non-empty, non-NULL value, or non-zero number. Have a look at the list of boolean evaluations in the PHP docs.

该构造if ($variable)测试以查看是否$variable评估为任何“真实”值。它可以是 boolean TRUE,或非空、非 NULL 值或非零数字。查看PHP 文档中的布尔评估列表

From the PHP documentation:

来自 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)

Note however that if ($variable)is not appropriate to use when testing if a variable or array key has been initialized. If it the variable or array key does not yet exist, this would result in an E_NOTICE Undefined variable $variable.

但是请注意,if ($variable)在测试变量或数组键是否已初始化时不适合使用。如果变量或数组键尚不存在,这将导致E_NOTICE Undefined variable $variable.

回答by Mat

If converts $variableto a boolean, and acts according to the result of that conversion.

If 转换$variable为布尔值,并根据该转换的结果进行操作。

See the booleandocs for further information.

有关更多信息,请参阅布尔文档。

To explicitly convert a value to boolean, 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 boolean argument.

要将值显式转换为布尔值,请使用 (bool) 或 (boolean) 强制转换。但是,在大多数情况下,强制转换是不必要的,因为如果运算符、函数或控制结构需要布尔参数,则会自动转换值。

回答by kevtrout

The following list explains what is considered to evaluate to falsein PHP:

以下列表解释了false在 PHP 中被视为评估的内容:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
  • 布尔值 FALSE 本身
  • 整数 0(零)
  • 浮点数 0.0(零)
  • 空字符串和字符串“0”
  • 一个元素为零的数组
  • 具有零成员变量的对象(仅限 PHP 4)
  • 特殊类型 NULL(包括未设置的变量)
  • 从空标签创建的 SimpleXML 对象

Every other value is considered TRUE (including any resource).

每隔一个值都被认为是 TRUE(包括任何资源)。

source: http://www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

来源:http: //www.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting

In your question, a variable is evaluated inside the if()statement. If the variable is unset, it will evaluate to false according to the list above. If it is set, or has a value, it will evaluate to true, therefore executing the code inside the if()branch.

在您的问题中,在if()语句中评估了一个变量。如果变量未设置,它将根据上面的列表评估为 false。如果它被设置,或者有一个值,它将评估为真,因此在if()分支内执行代码。

回答by deceze

It checks whether $variableevaluates to true. There are a couple of normal values that evaluate to true, see the PHP type comparison tables.

它检查$variable计算结果是否为true。有几个正常值计算为true,请参阅PHP 类型比较表

if ( )can contain any expressionthat ultimately evaluates to trueor false.

if ( )可以包含最终计算为or 的任何表达式truefalse

if (true)                  // very direct
if (true == true)          // true == true evaluates to true
if (true || true && true)  // boils down to true

$foo = true;
if ($foo)                  // direct true
if ($foo == true)          // you get the idea...

回答by Cups

Try looking at this old extended "php truth table" to get your head around all the various potholes waiting to burst your tyres. When starting out be as explicit as you can with any comparison operator that fork your code. Try and test against things being identicalrather that equal to.

尝试查看这个旧的扩展“ php真值表”,以了解所有等待爆胎的各种坑洼。开始时尽可能明确地使用分叉代码的任何比较运算符。尝试和测试事物是否相同而不是相等。

回答by kieran

Any of these are considered to be false (so that //code to be executed wouldnot run)

这些中的任何一个都被认为是错误的(因此//code to be executed would不会运行)

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
  • 布尔值 FALSE 本身
  • 整数 0(零)
  • 浮点数 0.0(零)
  • 空字符串和字符串“0”
  • 一个元素为零的数组
  • 具有零成员变量的对象(仅限 PHP 4)
  • 特殊类型 NULL(包括未设置的变量)
  • 从空标签创建的 SimpleXML 对象

All other values should be true. More info at the PHP Booleans manual.

所有其他值都应为真。PHP Booleans 手册中的更多信息。

回答by MoarCodePlz

It depends entirely on the value type of the object that you are checking against. In PHP each object type has a certain value that will return false if checked against. The explanation of these can be found here: http://php.net/manual/en/language.types.boolean.phpSome values that evaluate to false are

这完全取决于您要检查的对象的值类型。在 PHP 中,每个对象类型都有一个特定的值,如果检查该值将返回 false。这些解释可以在这里找到:http: //php.net/manual/en/language.types.boolean.php一些评估为假的值是

float: 0.0

浮动:0.0

int: 0

整数:0

boolean: false

布尔值:假

string: ''

细绳: ''

array: [] (empty)

数组:[](空)

object: object has 0 properties / is empty

对象:对象有 0 个属性/为空

NULL

空值

Its a bit different from most other languages but once you get used to it it can be very handy. This is why you may see a lot of statements such as

它与大多数其他语言有点不同,但是一旦你习惯了它,它就会非常方便。这就是为什么您可能会看到很多语句,例如

$result = mysqli_multi_query($query) or die('Could not execute query');

A function in PHP need only return a value type that evaluates to false for something like this to work. The OR operator in PHP will not evaluated its second argument IF the first argument is true (as regardless of the second argument's output, the or statement will still pass) and lines like this will attempt to call a query and assign the result to $result. If the query fails and the function returns a false value, then the thread is killed and 'Could not execute query' is printed.

PHP 中的函数只需要返回一个评估为 false 的值类型,这样的事情就可以工作。如果第一个参数为真,PHP 中的 OR 运算符将不会评估其第二个参数(因为无论第二个参数的输出如何,or 语句仍将通过),并且像这样的行将尝试调用查询并将结果分配给 $result . 如果查询失败并且函数返回假值,则线程被终止并打印“无法执行查询”。

回答by jeni

if a function successfully runs (true) or a variable exists (true) booleanthe if statement will continue. Otherwise it will be ignored

如果函数成功运行 (true) 或变量存在 (true) boolean,则 if 语句将继续。否则会被忽略