简体   繁体   中英

php problem: strpos function not working

why is the following php code not working:

$string = "123";
$search = "123";

if(strpos($string,$search))
{
    echo "found";
}else{
    echo "not found";
}

as $search is in $string - shouldn't it be triggered as found?

This is mentioned in the Manual: strpos()

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

In your case the string is found at the index 0 and in php 0 == false

The solution is to just use the strict comparator

echo strpos($string,$search) === false
     ? "not found"
     : "found";

Another one

echo is_int(strpos($string,$search))
     ? "found"
     : "not found";

Or something ... lets say interesting :D Just for illustration. I don't recommend this one.

echo strpos('_' . $string,$search) // we just shift the string 1 to the right
     ? "found"
     : "not found";

This is happening because the search string is being found at position 0. Try

if(strpos($string,$search) !== FALSE)

instead of

if(strpos($string,$search))

strpos returns the first offset where $search was found - 0 . 0 in turn evaluates to false . Therefore the if fails.

If $search was not found, strpos returns FALSE . First check the return value for !== FALSE , and then check the offset.

Thanks to everyone who pointed this out in the comments.

see: http://php.net/manual/en/function.strpos.php

From the manual :

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

In your example, you should use

$string = "123";
$search = "123";

if ( false !== strpos( $string, $search ) ) {
    echo "found";
} else {
    echo "not found";
}

strpos returns the numeric position of the string you want to search for if it finds it. So in your case, you want to be doing this instead:

$search = "123";
$string = "123";
if (strpos($string,$search)===false) { echo "not found"; }
else { echo "found"; }

basically it returns a false if it doesn't find your string

You can use this:

<?php

$string = "123";

$find = "123";

$strpos = strpos($string, $find);

if($strpos || $strpos === (int)0) {
    echo "Found it!";
} else {
    echo "Not Found!";
}

?>

Well documented issue explained here . strpos is simply returning '0'

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