The difference between if($args) and if(!empty($args)) in PHP
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:
if($args[2] == 1) {}
If element 2 does not exist in the array, an error will be reported. It should be written like this
if(!empty($args[2]) && $args[2] == 1) {}
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
