本文介绍了if($ variable)如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我已经多次看到它在脚本中使用过,现在我真的很想知道它寻找"什么.它什么都没有丢失.它只是if语句中的一个普通变量...我在任何地方都找不到关于此的任何结果,因此显然,发布此内容我会看起来很愚蠢.

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 ($variable)测试以查看$variable是否评估为任何真实"值.它可以是布尔值TRUE,也可以是非空,非NULL值或非零数字.看看PHP文档中的布尔值评估列表.

The construct if ($variable) tests to see if $variable evaluates 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.

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

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

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)如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:32