简体   繁体   中英

Why am I getting this unexpected result when using php strpos function?

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

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.

as per doc

strpos()

Find the numeric position of the first occurrence of needle in the haystack string. Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

so

strpos($string,'abc:') 

is returning 0. so it is echoing :

abc: false

In your case strpos() returning true/false result so you need to check according to return result try

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

You need to use Boolean comparison and it returns false only when there is no match

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

strpos($string, "abc") will return (int) 0
(int) 0 !== false ---> true statement
(int) 0 === true ---> false statement 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM