Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

The Strpos Trap in PHP

DZone's Guide to

The Strpos Trap in PHP

· Web Dev Zone
Free Resource

Try RAD Studio for FREE!  It’s the fastest way to develop cross-platform Native Apps with flexible Cloud services and broad IoT connectivity. Start Your Trial Today!

This week I found myself again using strpos as an example of the difference between the == and === operators in PHP. The strpos function tells us where a string occurs within another string, by returning the character offset. If the string isn't found, then the function returns false.

The problem arises because if we simply check that there's a positive return value from the function, we'll miss the case where the string appears at the start of the other string since the character offset will be zero:

$tagline = "PHP Made Easy" ;
if ( strpos ( strtolower ( $tagline ) , 'php' ) ) {
    echo 'php tagline: ' . $tagline ;
}
 

This code won't find the "if" to be true, since strpos returns zero and PHP will type juggle that to be false (debates about dynamically typed languages can be saved for another day)

Correct Use of ===



This is a great example of where the === operator really helps, as it can tell the difference between false and zero:

$tagline = "PHP Made Easy" ;
if ( false !== strpos ( strtolower ( $tagline ) , 'php' ) ) {
    echo 'php tagline: ' . $tagline ;
}
 

This time, we'll correctly get into the "if" even if the string appears at the start of the other string.

Not a particularly complex example but I think one that is simple enough to serve as a reminder as to what that extra = is for!

Get Your Apps to Customers 5X Faster with RAD Studio. Brought to you in partnership with Embarcadero.

Topics:

Published at DZone with permission of Lorna Mitchell, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}