Exclamation mark before variable - clarification required

I have been working with PHP for a long time, but for me it was always a mystery, the correct use of an exclamation mark (negative sign) in front of variables.

What does !$var indicate? Is var false , empty, not set, etc.?

Here are some examples 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'); } 

Will this example be valid?

I never use any of the above examples, I limit these if ($var) variables that have only boolean values. I just need to know if these examples are valid, so I can extend the use of if ($var) . They look very clean.

Thanks.

+6
source share
4 answers

if(! $a) matches if($a == false) . In addition, it should be borne in mind that type conversion occurs when using the == operator.
For more information, see the "Free comparisons with ==" section here . It follows that for the strings "0" and "" are FALSE ( "0"==false TRUE and ""==false also TRUE).

Regarding published examples:
Example 1
It will work, but you should note that both "0" and "are" empty "lines.

Example 2
He will work

+12
source

! cancels. true becomes false, and everything that evaluates to false becomes true.

If you write PHP and you don’t know all the operators by heart ... you should not write one line of code until you learn by heart:

http://php.net/manual/en/language.operators.php

These are the absolute basics.

+2
source

This is a logic tester. Empty or false.

0
source

This is a logical not operator, see the PHP manual for more details.

0
source

All Articles