Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php problem: strpos function not working

Tags:

php

substr

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?

like image 328
Fuxi Avatar asked May 23 '11 15:05

Fuxi


People also ask

How does Strpos work in PHP?

strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.

What does Strpos return in PHP if not found?

Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.


2 Answers

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";
like image 157
KingCrunch Avatar answered Oct 02 '22 01:10

KingCrunch


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))

like image 30
Ozair Kafray Avatar answered Oct 02 '22 01:10

Ozair Kafray