Loosely checking the return value from strpos() gives unintended result
Asked Answered
L

3

6

I'm using strpos() to find the position of a string in another string. I first check if the string is found at all in there. Here's my line:

if (
    strpos($grafik['data'], $ss1) <> false
    && strpos($grafik['data'], $ss2) <> false
    && strpos($grafik['data'], $ss1) < strpos($grafik['data'],$ss2)
)

I check if both strings are contained and then I want the first one to be placed before the second one. In the PHP manual it says that strpos() returns false when string is not found. However if my string starts at the zero position (strpos() returns 0 since its the beginning), it seems like this statement

strpos($grafik['data'], $ss1) <> false

is false. Somehow 0 is equal to false! How do I make the statement true when strpos() returns 0?

Loader answered 16/11, 2010 at 7:35 Comment(2)
See php 5 strpos() difference between returning 0 and false?.Foretoken
Also relevant: Why use !== FALSE to check stripos in php?Carpic
D
18

From http://www.php.net/manual/en/function.strpos.php:

Warning

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.

You have to use the === operator instead of ==.

In your case, instead of using <>, use !==:

strpos($grafik['data'], $ss1) !== false

This will return TRUE if $ss1 is found in $grafik['data']

Desman answered 16/11, 2010 at 7:38 Comment(0)
E
5

You need to check with ===. This will make sure you have exact false and not 0.

Eagre answered 16/11, 2010 at 7:39 Comment(0)
D
4

This function behaves unpredictably, so to be sure it'll have deterministic behavior use either

if(strpos($text,$string)===false)

or test it using a variable

$pos=strpos($text,$string); if($pos===false)

Deaf answered 24/11, 2011 at 23:40 Comment(1)
$pos here can still have a truthy or falsy value, so you should follow your own advice and use ===false instead of ! here, too. :)Schutt

© 2022 - 2024 — McMap. All rights reserved.