Jump to content

strpos() not functioning as expected


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
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!
}
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.