4

I was having trouble with a longer func i wrote, so i broke it down and it seems to be with the strpos() function.

Even though the needle is clearly present in the haystack it returns false, for the life of me i cant work out why, oddly though if i change the needle to "sam" in becomes true.. any idea why ?

function verify_url($url) {
    if (strpos($url, "http://")) {
        return $url;
    } else {
        echo "error";
    }
}


$url = "http://sam.com";

echo verify_url($url);
sam
  • 9,486
  • 36
  • 109
  • 160
  • You should use `===` instead of `==` at any time, except very very rare cases. `===` performs better than `==` and it never gives confusing conversion like `==`. – mpyw May 15 '13 at 12:28

2 Answers2

10

It is returning 0, not false. In the if test PHP evaluates integer value 0 as boolean value false.

Use strpos($url, "http://") !== false to check both value and data type. It is called strict comparison.

Manual: Comparison Operators and strpos().

Goran Rakic
  • 1,789
  • 15
  • 26
3

Replace your if (strpos($url, "http://")) with below one.

if (strpos($url, "http://") !== false)

It's giving 0 (and not false) because it found http:// at 0th position

Smile
  • 2,770
  • 4
  • 35
  • 57