Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does an exclamation mark before a function really mean in PHP

Just as in the title, what does an exclamation mark before a function really mean in PHP?


For example is the following statement:

if (!stripos($haystack, $needle)) {}

the same as this:

if (stripos($haystack, $needle) === FALSE) {}

or this:

if (stripos($haystack, $needle) == FALSE) {}


Any clarification would be appreciated

like image 283
n1te Avatar asked Apr 07 '12 07:04

n1te


1 Answers

The ! preceding the function is the same as...

if (stripos($haystack, $needle) == FALSE) {}

It's the same because it is a == comparison which doesn't check types.

It's called the negation unary operator. It flips the Boolean value (coercing to Boolean if need be) of a value.

For example...

! 0;    // True
! 1 ;   // False
! '';   // True
! true; // False
!! 0    // False 

The !! trick is handy in languages without a (bool) cast. By flipping a value twice, you get the Boolean version of its original value.

like image 167
alex Avatar answered Nov 14 '22 22:11

alex