How can I be a good

PHP String Contains and Identical Operators

Jon Volks
Written By | @webproninja

PHP doesn’t have an operator for CONTAINS like ColdFusion but there is a work around. What we are going to use is the strpos() function which pretty much returns the position of one string within another string. Example: strpos(“You are here!”, “are”); The result will return 4 (remember PHP starts on 0). This will work great in an IF statement, however we have one problem. What happens if the search is the very first position, this would return 0 and if put in an IF statement, then it will not work. We need to use the identical operator. Let’s take a look at the correct code:

$a = "You are here!";
if(strpos($a, "are") !== false) {
echo "true";

If strpos() does not find anything it returns false, otherwise when it does find something, it will return an integer. So what the identical operator does is check if both sides of the equation are the same data type. Therefore 0 (int) does not equal false (boolean). With this, you’ll be able to use PHP and contains a string.

A === B : A is equal to B and the same data type.
A !== B : A  is not equal to B or they are not the same data type.

What do you think? Do you use identical operators?

About The Author

Jonathan Volks is currently a Web Programmer at Skidmore College in Upstate New York. He enjoys everything about the Internet; from Search Engine Optimization to Web Programming. His hobbies include landscape photography and hiking the Adirondacks.

Leave a Reply

Your email address will not be published. Required fields are marked *