-2

After reading How do I check if a string contains a specific word in PHP? and the documentation about strpos() at http://php.net/manual/en/function.strpos.php, I try an alternative of the first link, instead of !==, I use >= 0

$a = "Hello";
$b = "a";
if(strpos($a, $b) >= 0) {
  echo 'string found';
} else {
  echo 'string not found';
}

prints 'string found' and not 'string not found'? $b is obviously not in $a, so strpos() should return false, hence it should enter the else, what's going on here?

Community
  • 1
  • 1
絢瀬絵里
  • 1,013
  • 2
  • 14
  • 27
  • `>=` 0 is not an alternative of `!==`. It is in this context close to `!=`, which is totally different from `!==`. – eis Nov 23 '12 at 08:15
  • possible duplicate of [PHP - How to check if a string contain specific words](http://stackoverflow.com/questions/4366730/php-how-to-check-if-a-string-contain-specific-words) – tereško Nov 23 '12 at 23:58

3 Answers3

2

In that case, strpos did return false. However, any value other than 0 is treated as true in php, including negatives that is, and 0 is treated as false. So,

if(strpos($a, $b) >= 0)

is evaluated into

if(false >= 0)

and then

if(0 >= 0)

which is true

You should use !== false instead, so if(strpos($a, $b) !== false)

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
絢瀬絵里
  • 1,013
  • 2
  • 14
  • 27
1

Please read the manual: php.net/manual/en/function.strpos.php

You will notice that strpos will return false is $b is not in $a. You will need to check it this way:

<?php
$a = "Hello";
$b = "a";
if(strpos($a, $b) !== false) {
  echo 'string found';
} else {
  echo 'string not found';
}
eisberg
  • 3,731
  • 2
  • 27
  • 38
0
if(strpos($a, $b) >= 0) 
strpos($a, $b) returns false
if(false >= 0) is true.

Here we need to check type.

som
  • 4,650
  • 2
  • 21
  • 36