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

19,508

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.

Share:
19,508
n1te
Author by

n1te

49206c757620636f64696e672e200d0a0d0a453a206e3174656c6565745b61745 d5b656d61696c2e73797374656d2e637265617465642e62792e676f6f676c655d

Updated on June 13, 2022

Comments

  • n1te
    n1te almost 2 years

    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

  • n1te
    n1te about 12 years
    Thanks, this is the clarification I was looking for
  • Taha Paksu
    Taha Paksu about 12 years
    ..And thanks for the appreciation. I'm trying to help here. Doesn't my answer make sense to you?
  • n1te
    n1te about 12 years
    Your answer was good but alex's answer was for me easier to understand. Btw. It wasn't me who voted you down.
  • Taha Paksu
    Taha Paksu about 12 years
    No I was commenting to another comment, sorry. he deleted after I wrote this.
  • Pacerier
    Pacerier over 10 years
    @alex, How did you know it coerce to boolean if need be? Did the docs meantion about it? php.net/manual/en/language.operators.logical.php
  • user3167101
    user3167101 over 10 years
    @Pacerier It says TRUE if $a is not TRUE.
  • Pacerier
    Pacerier over 10 years
    @alex, Why does "is not TRUE" involve coercing? Isn't "is not TRUE" simply !== ?