简体   繁体   中英

PHP a better way for check non-empty?

The common way for check non-empty var is:

if (!empty($var)) { ... }

Why can't we just use:

if ($var) { ... }

They're the same actually, right?

Ref: http://php.net/manual/types.comparisons.php

!empty($var) is exactly the same as just $var , except that with empty no error will be thrown if $var doesn't exist. empty is more or less shorthand for !isset($var) || !$var !isset($var) || !$var .

You should never use empty if you expect your variable to exist, because then you're just needlessly suppressing error reporting. Only use empty if you legitimately expect the variable to possibly not exist. This should rarely if ever be the case, if you're initialising your variables properly.

See The Definitive Guide To PHP's isset And empty for an in-depth discussion of this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM