Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strpos() returning false, when needle is in haystack [closed]

Tags:

php

strpos

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);
like image 460
sam Avatar asked Oct 15 '25 13:10

sam


2 Answers

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().

like image 147
Goran Rakic Avatar answered Oct 19 '25 15:10

Goran Rakic


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

like image 23
NullPointer Avatar answered Oct 19 '25 14:10

NullPointer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!