Home  >  Article  >  Backend Development  >  The difference between if($args) and if(!empty($args)) in PHP

The difference between if($args) and if(!empty($args)) in PHP

WBOY
WBOYOriginal
2016-12-01 01:27:551931browse

There is often confusion when coding. How to determine if a variable is not empty:
Method 1: if($args){...do something..}
Method 2: if(!empty($args)) {.. .do something...}

Do these two methods have the same effect? ​​Which one is better in terms of execution efficiency?
Thanks for the answer!

Reply content:

There is often confusion when coding, to determine if a variable is not empty:
Method 1: if($args){...do something..}
Method 2: if(!empty($args)) {.. .do something...}

Do these two methods have the same effect? ​​Which one is better in terms of execution efficiency?
Thanks for the answer!

It’s different, if $args == 0, then $args == false

In most cases, !empty is safer. It can use unset variables as parameters without reporting an error, for example:

<code class="php">if($args[2] == 1) {}</code>

If element 2 does not exist in the array, an error will be reported. It should be written like this

<code class="php">if(!empty($args[2]) && $args[2] == 1) {}</code>

The first method will cause a warning when $args is not defined. Any Error in PHP will cause considerable performance loss. This is mainly due to the error handling mechanism of PHP.

Under the second method, empty can handle undefined parameters and avoid warnings. In addition, empty is an instruction rather than a function, and its operating efficiency will not be much slower than the first method.

In short, if you can ensure that $args is defined, you can use the first one. If not, it is recommended to use the second option.

  • Method 1: It involves type conversion

  • Method 2: empty determines non-empty values, and empty values ​​include

<code>int 0
float 0.0
string '0'
string ''
array array()
boolean false
NULL
$var(一个定义了但为空值的变量)</code>

The key lies in the judgment of if() and empty().
Copy the log written, but only if:

<code>布尔值FALSE身.
整形值0.
浮点类型0.0
空字符串'',以及字符串'0';//这里是重点
不包含任何元素的数组.
不包含任何成员的对象.(仅php 4.0)
特殊类型NULL
其他任何类型的数据都被默认为TRUE(包括资源类型)
-1也为TRUE(无论正负)</code>

This is the judgment result of if. If it is empty, please refer to the documentation.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn