phpstringstrpos

strpos() in ternary expression unexpectedly executes false branch when finding a match at the start of the string


I am trying to use PHP's strpos() function to search for a string within another string. I have performed 2 different searches, both containing a colon character. The only difference I can see between the two is whether the colon appears at the beginning of the 'needle' or the end.

My code is as follows:

<?php
$string = 'abc:def';
echo strpos($string,'abc:') ? 'abc: true' : 'abc: false';
echo ' / ';
echo strpos($string,':def') ? ':def true' : ':def false'; 

The output I am getting is abc: false / :def true. I don't understand why, and was hoping someone can explain it to me. You can see a working example here:

http://ideone.com/MyEn5d


Solution

  • Strpos returns the position of a given string (needle) in other string (stack). See reference - strpos. Correct usage of strpos (notice it's !== not !=, since we want to also check for type):

    $string = 'abc:def';
    echo strpos($string,'abc:') !== false ? 'abc: true' : 'abc: false';
    echo ' / ';
    echo strpos($string,':def') !== false ? ':def true' : ':def false'; 
    

    Summing up, strpos returns the numeric value that is a position (so for example 0 or 5) or false when the value is not found.

    As to why your snippet

    echo strpos($string,':def') ? ':def true' : ':def false'; 
    

    returns true - in PHP every non-zero integer is treated as true, if you are comparing it as boolean, and your strpos returned value bigger than zero (probably '4' in this example), so it was considered true. See here for more details.