Jump to content

strpos() not functioning as expected


davidannis

Recommended Posts

I want to use a different configuration file if I am on my test server, so I was testing to see if the URL begins with test but it is not working. I have done this before but I must be doing something differently because I expect strpos('test', $_SERVER['HTTP_HOST']) to return a 0 but it is returning a bool false.

 

I have tested it with the following code:

echo $_SERVER['HTTP_HOST'].'<br>';
$x = strpos('test', $_SERVER['HTTP_HOST']);
var_dump($x);
die();

which gives me the following output:

test.ezvaluation.com
bool(false) 

Why?

 

Link to comment
https://forums.phpfreaks.com/topic/285694-strpos-not-functioning-as-expected/
Share on other sites

strpos:

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

You're calling it with the arguments in the wrong order. You're checking to see if the string 'test.ezvaluation.com' exists within the string 'test'.

also note to make sure to do a strict comparison when using strpos.

 

$foo = "bar";
if (strpos("bar",$foo)) {
  // found?
} else {
  // not found?
}
In this example, the condition should be true, but strpos returns the position of the found needle. Since it is at the beginning, it will return 0. Since 0 is a falsey type, the condition will evaluate false, even though it was found.

 

So you need to do something like this:

 

$foo = "bar";
if (strpos("bar",$foo)!==false) { // <-- !== not != for strict comparison
  // found!
} else {
  // not found!
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.