PHP strpos function not working – It does, just not the way you expect

strpos($needle,$hey_stack);  returns the exact the position of the the needle in the heystack.

The powerful/easy-to-use if(strpos(‘hey’,’hey world’)){//do something}else{//do something else} feature of PHP is also a major weakness if you do not fully understand how if statements in PHP work.

This comes back to a basic programming concept of beginning counting from zero. In the case of strpos(‘hey’,’hey world’) the result is zero.

PHP if statements evaluate the following as false:

  • false
  • 0
  • NULL
  • '' (an empty string)

As strpos(‘hey’,’hey world’); returns zero as ‘hey’ is at string position 0 a simple if statement in PHP would return false.

The correct way is to capture for a real false:

if (strpos('hey', 'hey world')!== false)
{
     //do something
}
else
{
    //do something else
}

 

Advertisements

One thought on “PHP strpos function not working – It does, just not the way you expect

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s