2

Can the relational operator === (used for identical) be used interchangeably with the != operator" and get the same results? Or will I eventually run into issues later down the road when I do larger programs?

I know I will get the same results in the example below, will this always be true?

//example 1  
   <?php
        $a = 1; //integer
        $b = '1'; //string
        if ($a === $b) {     
            echo 'Values and types are same'; 
        }
        else {
            echo 'Values and types are not same';
        }
    ?> 

 // example 2
    <?php
        $a = 1; //integer
        $b = '1'; //string
        if ($a != $b) {     
            echo 'Values and types are not same'; 
        }
        else {
            echo 'Values and types are same';
        }
    ?>
  • Why would you want to do this? PHP's operators are confusing enough as they are. – BoltClock Oct 05 '12 at 04:15
  • 1
    != is not equal, you need !== to have not equal and not same type. http://php.net/manual/en/language.operators.comparison.php – ace Oct 05 '12 at 04:17
  • Check this question and you will not like to use `==` or `!=`, http://stackoverflow.com/questions/12598407/php-expresses-two-different-strings-to-be-the-same – xdazz Oct 05 '12 at 04:18
  • I see this being helpful when validating forms and checking if user has special privileges to see specifice pages based on specific database fields. – Jordan Smith Oct 05 '12 at 04:18
  • http://stackoverflow.com/questions/589549/php-vs-operator – Habib Oct 05 '12 at 04:19

2 Answers2

6

Short answer is, no, you can't interchange them because they check for different things. They are not equivalent operators.

You'll want to use !==

It basically means both values being compared must be of the same type.

When you use ==, the values being compared are typecast if needed.

As you know, === checks the types also.

When you use !=, the values are also typecast, whereas !== checks the values and type, strictly.

Stegrex
  • 4,004
  • 1
  • 17
  • 19
2

You're essentially asking whether !($a != $b) will always be identical to $a === $b. The simple answer is: no. !($a != $b) can be boiled down to $a == $b, which is obviously not the same as $a === $b:

php > var_dump(!('0' != 0));
bool(true)

php > var_dump('0' === 0);
bool(false)

!== is obviously the opposite of ===, so !($a !== $b) will always be identical to $a === $b.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • 1
    It's asking `if ($a === $b) true; else false;` vs. `if ($a != $b) false; else true;`, which is what I'm explaining. – deceze Oct 05 '12 at 04:26