Why when we want to use strpos to search for a word in a string, we have to say that it is not false?

1

I had to find a way to find a word within a php string and I got it, but I do not understand very well why. For example, would not it be easier to put == true before! == false? and what do we get exactly that is not false? Here is an example of a code that works perfectly.

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}
    
asked by David Palanco 30.10.2018 в 17:30
source

1 answer

1

The problem is that strpos returns the index of the first character where the string is found. In your example there is no difference between using == true or !== false but in other cases it is not the same. For example, strpos("I love php","I") would return 0 . In PHP the 0 in addition to its int value, also has a boolean value that is FALSE . So if you do this: if(strpos("I love php","I") == true) is going to return FALSE , even though the sub-chain I is in the string I love php . That's the reason why !== false is preferable, because it works in all cases.

    
answered by 30.10.2018 / 17:33
source