Stupid question, I know, but if I don't know whether a variable $var
is set or not, should I use
isset[$var] && !empty[$var]
to check if it has any value in it, or is
!empty[$var]
enough? Would there be a problem if $var
is null in the second case?
asked Nov 30, 2011 at 22:57
federico-tfederico-t
11.7k17 gold badges64 silver badges109 bronze badges
4
isset
and empty
are both language constructs. And empty[]
internally does an isset
check first, then negates that, or alternatively also checks for values that equate FALSE
in boolean context.
So yes, !empty[]
is sufficient.
answered Nov 30, 2011 at 23:00
7
Yes, you can drop the isset[]
:
empty[]
is the opposite of[boolean] var
, except that no warning is generated when the variable is not set.
You can see this with the following code:
error_reporting[E_ALL];
var_dump[empty[$var]];
bool[true]
[Note the lack of an undefined variable warning]
answered Nov 30, 2011 at 23:00
Tim CooperTim Cooper
153k37 gold badges319 silver badges272 bronze badges
You should use isset[], as !empty[] will return false if your $var is 0.
answered Nov 30, 2011 at 23:01
kylexkylex
13.9k31 gold badges112 silver badges173 bronze badges
1
I think you can drop that isset[]
completely in case you're using empty[]
, because empty[]
checks whether variable is set first, too
so after all, use
if [!empty[$var]] {
//isset and not empty
}
answered Nov 30, 2011 at 23:00
Martin.Martin.
10.3k3 gold badges40 silver badges67 bronze badges
0
PHP has two special shorthand conditional operators.
- Ternary Operator
- Null Coalescing Operator
PHP Ternary Operator
The ternary operator is a short way of performing an if conditional.
Ternary Syntax
[] ? [] : []
- If the condition is true, the result of on true expression is returned.
- If the condition is false, the result of on false expression is returned.
- Since PHP 5.3, you can omit the on true expression. [condition] ?: [on false] returns the result of condition if the condition is true. Otherwise, the result of on false expression is returned.
PHP Ternary Operator Example