The '===' operator in PHP
Translation of the original in Catalan. Read it in: CatalàCastellano
With how long I've been programming in PHP, I had never found myself needing to use this operator. In fact, what I should say is that I had never imagined this operator existed. Sure, you all know the '==' which simply serves to compare whether two values are equal. Well then, the difference with '===' is that it compares that they are equal and of the same type. For me it served to solve a very simple problem that was becoming very complicated.
For example, if we have an array and we do a search for a value inside the array with the array_search command, it will return the key that identifies the row of the array where the value we're looking for is. But if the value isn't found in the array it will return a false. If we want to know whether it was found or not, we can do a:
if ( $clau_retornada == false )
The little problem with this code is that false is equal to 0 and if the search returns the key 0 as a result (first position of an array), then we'll have an ambiguous answer. Well then, if the condition had been:
if ( $clau_retornada === false )
We wouldn't have had this problem, since the zero returned by the array_search function, if it were a key, would have had a numeric or alphanumeric type, but not a boolean type. So, thanks to the operator we're talking about we could avoid the ambiguity of the value returned by the array_search function.
2 comments
Comments from the old blog, as they were written. Comments are closed.
Oriol (l-altre)
On més he emprat aquest operador és quan es crida la funció strpos, que retorna la posició on es troba un substring dins d'un string.
És força usual trobar-se amb codis incorrectes que fan el següent:
if (strpos($cadena,$cerca)==false) {
echo "no es troba $cerca a $cadena";
}
Dic incorrectes, perquè amb $cadena="hola" i $cerca="h" el resultat de strpos seria 0 i per tant 0==false, amb lo qual ens llençaria el "no es troba cadena" quan realment no és així.
La sintaxi correcte, com bé comentes, seria amb l'operador ===
if (strpos($cadena,$cerca)===false) {
echo "no es troba $cerca a $cadena";
}
—
[1]
Bona aplicació i reflexió. De fet, trobo molt greu que fins ara no hagi descobert això i em fa molta ràbia. M'hagués fet moltíssims favors en el passat. Però bé, ja se sap que no es pot saber tot ;)