Is there any advantage to writing a PHP conditional like this:
if ($variable != NULL) {
versus
if (!empty($variable)) {
versus
if ($variable) {
Aren’t they all same thing? It seems like the last is always the simplest if you are just trying to tell whether the variable exists or not. Thanks for helping me understand the difference here. I missed the first day of PHP 101.
I agree with Sean but I’ll outline what each does in plain English:
$variablewill beNULLif it hasn’t been set. This is practically the same asissetand the same as the variable being undefined.Generally, this checks whether
$variableas a string ((string) $variable) has astrlenof 0. Howevertruewill make it returnfalse, as will integers that aren’t 0 and empty arrays. For some reason (which I believe to be wrong)$variable = '0';will returntrue.This true/false check acts like
(boolean) $variable– basically whether the variable returns true when converted to a boolean.One way to think about it is that it acts the same as empty, except returns the opposite value.
For more information on what I mean by
(boolean) $variable(type casting/juggling) see this manual page.(PHP devs: this is mainly by memory, if I’m wrong here please correct me!)