Jump to content

strpos() not functioning as expected


davidannis
Go to solution Solved by 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
Share on other sites

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!
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.