I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.
What does !$var
indicate? Is var false
, empty, not set etc.?
Here are some examples that I need to learn...
Example 1:
$string = 'hello';
$hello = (!empty($string)) ? $string : '';
if (!$hello)
{
die('Variable hello is empty');
}
Is this example valid? Would the if statement really work if $string
was empty?
Example 2:
$int = 5;
$count = (!empty($int)) ? $int : 0;
// Note the positive check here
if ($count)
{
die('Variable count was not empty');
}
Would this example be valid?
I never use any of the above examples, I limit these if ($var)
to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var)
statements. They look really clean.
Thanks.