Is There a Need to Check for isset() and empty() Together in PHP?

No! There is no need to check for both isset() and empty() together because empty() does not generate a warning when a variable is not set. Therefore:

// instead of doing:
(! isset($foo[0]) || empty($foo[0]))

// or:
(! isset($foo[0]) || ! $foo[0])

// you could/should use:
(empty($foo[0]))

Same is true when checking for not empty:

// instead of doing:
(isset($foo[0]) && ! empty($foo[0]))

// or:
(isset($foo[0]) && $foo[0])

// you could/should use:
(! empty($foo[0]))

Remember, though, that empty() is not a replacement for isset(). In fact, they're both used for distinct purposes; isset() is used for checking if a variable is set and not null, while empty() is used for checking if a variable is not set or has a falsy value.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.