Note - I know pretty much about empty() and isset(), what I am asking is the most proper/efficient way of using them.
I've just saw at php.net this sentence under empty()
reference:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
But again, as I'm mainly working now on other people's apps (either standalone projects, websites using cms or even frameworks) many many times I've seen people writing:
if (isset ($var) && $var != '')
// or
if (isset ($var) && !empty($var))
(mainly with $_GET and $_POST variables, but not only)
As far as I understand manual, snippet below is equivalent:
if (!empty($var))
Or am I missing something? What is technically the best way to check existense of variable with value?
I know both functions, their destinations. I just want to know if empty()
is all needed to check if is variable set and given value. I know that it works, but is it 100% proper and safe?
Op codes generated from isset($var) && !empty($var)
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > EXT_STMT
1 ISSET_ISEMPTY_VAR 12800000 ~0 !0
2 > JMPZ_EX ~0 ~0, ->6
3 > ISSET_ISEMPTY_VAR 11800000 ~1 !0
4 BOOL_NOT ~2 ~1
5 BOOL ~0 ~2
6 > FREE ~0
4 7 > RETURN 1
and from !empty($var)
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > EXT_STMT
1 ISSET_ISEMPTY_VAR 11800000 ~0 !0
2 BOOL_NOT ~1 ~0
3 FREE ~1
4 4 > RETURN 1
So yes it does repeat ISSET_ISEMPTY_VAR
but !$empty
. It depends on the value passed, but it it doesnt exist the top way is one opcode less BOOL_NOT
. but if it does exist, the bottom way is quicker.
Though its unlikely this is going to be a bottleneck in any application