$headspace == “a little crazy!”

โ€”

by

in

Here is the hard won PHP knowledge of the weekend. Contemplate the following…

$haystack = “Hello World!”;

Now, let’s imagine you want to test to see if it contains the string “Hello”. You would think that the following code would do it:

<?php

// this code will not always work as expected
$haystack = “Hello World!”;
$needle = “Hello”;
if( strpos( $haystack, $needle ) ){
    echo “Found it!”;
}else{
     echo “Not found!”;
 }

?>

You would be wrong. See, the strpos() function is a bit  funky. It returns either false if the string could not be found, or the position of the string if it could be found. Soulhuntre I hear you cry, that will work perfectly!

Except of course if the tested string is at the beginning of the larger string (needle and haystack respectively). If so, then the return from strpos() is 0 and chaos ensues. Thanks to the normally incredibly helpful implicit conversions of PHP the string found at the beginning will be at position 0 and will evaluate to false in the if() above.

What you need in this case is the === operator. That is three “=”‘s in a row. This says that something is equal only if it is the same data type and has the same value. No implicit conversions. The following code will work as expected:

<?php

// this code will work as expected $haystack = “Hello World!”;
 $needle = “Hello”;

if( strpos( $haystack, $needle ) === false ){
    echo “The string was not found!”;
}else{
    echo “Found it!”;
}

if( strpos( $haystack, $needle ) !== false ){
    echo “The string was found!”;
}else{
    echo “The string was not found!”;
} if( strpos( $haystack, $needle ) === 0 ){
    echo “The string was at the beginning!”;
}else{
    echo “The string was not there, or not at the beginning!”;
}

 ?>

Enjoy!