Php – The best practice for not null if statements

php

I've been writing my "If this variable is not empty" statements like so:

if ($var != '') {
// Yup
}

But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:

if (!($error == NULL)) {
/// Yup
}

This actually looks longer than my approach, but is it better? If so, why?

Best Solution

Rather than:

if (!($error == NULL))

Simply do:

if ($error)

One would think that the first is more clear, but it's actually more misleading. Here's why:

$error = null;

if (!($error == NULL)) {
    echo 'not null';
}

This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:

$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;

The second conditional if ($error) makes it more clear that type casting is involved.

If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)