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

Source: Internet
Author: User
Tags php error
There is often a confusion when coding, judging a variable is not NULL:
Way 1:if ($args) {... do something ...}
Way 2:if (!empty ($args)) {...} do something ...}

Do the two approaches work the same way, and what's better in execution efficiency?
Thanks for the answer!

Reply content:

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

Do the two approaches work the same way, and what's better in execution efficiency?
Thanks for the answer!

Not the same, if $args = = 0, that $args = = False

In most cases!empty will be more secure, and it will not give an error if the unset variable is used as a parameter, for example:

if($args[2] == 1) {}

If the array does not have element 2, an error will be found. It should be written.

if(!empty($args[2]) && $args[2] == 1) {}

The first method is $args not defined in the case of a warning, any error in PHP will cause a significant performance loss, mainly due to PHP error handling mechanism.

The second method can empty handle undefined parameters, avoiding warnings. emptythe other is the instruction rather than the function, and the running efficiency is not much slower than the first.

In short, if you can guarantee $args that you have defined, you can use the first. If not, it is recommended to use the second type.

    • Mode 1: It involves a type conversion.

    • The 2:empty method determines the non-null value, and the null value includes

int 0float 0.0string '0'string ''array array()boolean falseNULL$var(一个定义了但为空值的变量)

The key is in the judgment with if () and empty ().
Copy writes the log bar, but only if:

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

This is the if judgment result, empty words, look at the document bar.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.