Php problem: strpos function not working

why the following PHP code does not work:

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

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

+4
source share
7 answers

This is specified in Manual: strpos ()

This function can return Boolean FALSE, but it can also return a non-boolean value that evaluates to FALSE, such as 0 or "". Please read the Booleans section for more information. Use the === operator to check the return value of this function.

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

The solution is to simply use a strict comparator

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

Other

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

Or something ... let's say interesting: D For illustration purposes only. I do not recommend this one.

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

This is because the search bar is at position 0. Try

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

instead

if(strpos($string,$search))

+3
source

strpos returns the first offset, where $search found is 0 . 0 , in turn, evaluates to false . Therefore, if does not work.

If $search 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

+2
source

From the manual :

This function can return a Boolean FALSE, but it can also return a non-boolean value that is FALSE, for example 0 or ". Please read the Booleans section for more information. Use the === operator to check 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"; } 
+2
source

strpos returns the numeric position of the string you want to find if it finds it. So in your case, you want to do this instead:

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

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

+1
source

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!"; } ?> 
0
source

A well-documented issue is explained here . strpos just returns "0"

0
source

All Articles