Você está na página 1de 1

What is the difference between == and === in PHP?

When comparing values in PHP for equality you can use either the == operator or the === operator. Whats the difference between the 2? Well, its quite simple. The == operator just checks to see if the left and right values are equal. But, the === operator (note the extra =) actually checks to see if the left and right value s are equal, and also checks to see if they are of the same variable type (like whether they are both booleans, ints, etc.). An example of when you need to use the === operator in PHP Its good to know the difference between the 2 types of operators that check for e quality. But, its even better to understand when and why you would need to use th e === operator versus the == operator. So, we want to give you an example of whe n you must use the === operator: When developing in PHP, you may find a time whe n you will need to use the strpos function you should read more about this funct ion here in order to understand our example (dont worry its a very quick read). When using the strpos function, it may return 0 to mean that the string you are searching for is at the 0th index (or the very first position) of the other stri ng that you are searching. Suppose, for whatever reason, we want to make sure th at an input string does not contain the string xyz. Then we would have this PHP co de: //bad code: if ( strpos( $inputString, xyz ) == false ) { // do something } But, there is a problem with the code above: Because $strpos will return a 0 (as in the 0th index) if the $strpos variable happens to have the xyz string at the v ery beginning of $inputString. But, the problem is that a 0 is also treated as f alse in PHP, and when the == operator is used to compare 0 and false, PHP will s ay that the 0 and false are equal. That is a problem because it is not what we w anted to have happen even though the $inputString variable contains the string xy z, the equality of 0 and false tells us that $inputString does not contain the xyz string. So, there is a problem with the way the return value of strpos is compar ed to the boolean value of false. But, what is the solution? Well, as you probably guessed, we can simply use the === operator for comparison. And, as we describe d earlier, the === operator will say that the 2 things being compared are equal only if both the type and value of the operands are also equal. So, if we compar e a 0 to a false, then they will not be considered equal which is exactly the ki nd of behavior we want. Here is what the good code will look like: //good code: if ( strpos( $inputString, xyz ) === false ) { // do something }

Você também pode gostar