1

When I use strpos(), it isn't able to locate "[" if that bracket is the first character in the string. How can I overcome this issue and why is this happening?

$name = "[johnny";
    if(strpos($name, "[") != false){
          echo "Bracket found!";}else{
            echo "Not found";
          }

In the above code, I get "Not found" when it shouldn't be the case.

$name = "jo[hnny";
    if(strpos($name, "[") != false){
          echo "Bracket found!";}else{
            echo "Not found";
          }

But this case correctly returns "Bracket found!"

green555
  • 69
  • 7
  • 2
    Use `!== false`. Example [here](https://phpize.online/?phpses=e92c28408fa58af2f25bf605d19e45f8&sqlses=null&php_version=php7&sql_version=mysql57) – Paul T. Feb 28 '21 at 03:47
  • 1
    In your first example, `strpos` returns 0, which is interpreted loosely as false. As Paul said, !== requires a strict match. You can also check if the return result is greater than -1. – Liftoff Feb 28 '21 at 03:50
  • I see! so when using strpos() I have to always use either === or !==? – green555 Feb 28 '21 at 03:52
  • 1
    Always is a strong word. In this case, where you're checking if the substring is present in the haystack string, then yes, you should use !==. === and !== mean equal in both type and value, whereas != and == are just equal in value. 0 == false because in binary, 0 is false and 1 is true, but 0 !== false. – Liftoff Feb 28 '21 at 03:52

1 Answers1

2

You must use !== false (double equals sign)

From the strpos manual page:

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

And the example given on the page:

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}
rjdown
  • 9,162
  • 3
  • 32
  • 45