Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: if (!$val) VS if (empty($val)). Is there any difference?

Tags:

I was wondering what's the difference the two cases below, and which one is recommended?

$val = 0;  if (!$val) {   //True }  if (empty($val) {   //It's also True } 
like image 408
Bachx Avatar asked Aug 22 '11 00:08

Bachx


People also ask

Is NULL and empty string the same in PHP?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

Should I use empty or Isset?

The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not. The isset() function will generate a warning or e-notice when the variable does not exists. The empty() function will not generate any warning or e-notice when the variable does not exists.

How do you check if a variable is empty or not in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.


2 Answers

Have a look at the PHP type comparison table.

If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.

like image 100
Shi Avatar answered Nov 03 '22 00:11

Shi


If you use empty and the variable was never set/created, no warning/error will be thrown.

like image 22
Nican Avatar answered Nov 03 '22 01:11

Nican