Equality vs. Identity in PHP if statements.

From time to time I meet developers that do not know the difference between == (equality) and === (identity) in PHP. Hopefully this post will clear it up for you. Here are a few examples of PHP is statements.

1
2
3
4
5
6
7
8
9
10
11
12
13
    if( 1 == true ) { /* do something */ }
 
    if( 1 === true ) { /* do something */ }
 
    if( true == true ) { /* do something */ }
 
    if( true === true ) { /* do something */ }
 
    if( 1 == 1 ) { /* do something */ }
 
    if( 1 === 1 ) { /* do something */ }
 
    if( 1 === '1' ) { /* do something */ }

Above, I wrote 7 quick and simple if statements. 1) In PHP 0 equates to FALSE, and any other number equates to true. In this statement, 1 IS EQUAL to true; 2) This will fail, since 1 is not EXACTLY the same as true; 3) This will work, since true IS EQUAL to true; 4) This will work, since true is EXACTLY the same as true; 5) This will work, since 1 IS EQUAL to 1; 6) This will work, since 1 is EXACTLY the same as 1; 7) This will fail, since 1 is NOT EXACTLY the same as ‘1’ (integer vs string); You may ask why you need to know this, and how this is relevant to PHP. Here is a good reason: The strpos() function will return an integer number or a boolean false. Lets say your needle is at position 0, the function will return 0. If you used the equality check, this would equate to false, since PHP considers a 0 as false. Consider this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
    $string = "This is an example string";
 
    /*
     * This will fail your check, even though, the needle was found.
     */
    $pos = strpos( $string, 'This');
    if( $pos == false )
    {
        echo "This string does not contain the word: This";
    }
 
    /*
     * This will work since if the needle could not be found.
     */
    $pos = strpos( $string, 'Word');
    if( $pos === false )
    {
        echo "This string does not contain the word: Word";
    }
Posted on in PHP