CMSCSS
CMSCSS

Reputation: 2176

Having trouble with basic php if/else statement

This works if 'test1' is in the url:

<? if(strpos($_SERVER['HTTP_HOST'], 'test1') !== FALSE) : ?>
  <p>Do something</p>
<? else : ?>
  <p>Do something else</p>
<? endif ?>

This doesn't work if 'test1' is in the url:

<? if(strpos($_SERVER['HTTP_HOST'], 'test1') OR strpos($_SERVER['HTTP_HOST'], 'test2') !== FALSE) : ?>
  <p>Do something</p>
<? else : ?>
  <p>Do something else</p>
<? endif ?>

Questions:

1. When I try to run the second option, php outputs "Do something else" every time - I know it's basic but why is this?

2. Why doesn't == TRUE work in this instance, only !==FALSE works.


Any help would be much appreciated - I've spent a scary amount of time researching this so sorry if it's because of a dumb mistake.

Cheers

Upvotes: 2

Views: 66

Answers (2)

Society43
Society43

Reputation: 737

try this

if(strpos($_SERVER['REQUEST_URI'], 'test1') OR strpos($_SERVER['REQUEST_URI'], 'test2') !== FALSE){ 
  echo"<p>Do something</p>";
} else {
  <p>Do something else</p>
}

Upvotes: 0

Kevin
Kevin

Reputation: 41873

You shouldn't test loosely with == TRUE because you might get a false positive, remember that 0 is falsy when its tested loose and getting 0 in strpos is valid since that actually is the position of where the needle exists relative to the beginning of your string.

Consider this snippet:

<?php $_SERVER['HTTP_HOST'] = 'test1.com'; ?>
<?php if(strpos($_SERVER['HTTP_HOST'], 'test1') == TRUE): ?>
  <p>Do something</p>
<?php else : ?>
  <p>Do something else</p>
<?php endif; ?>

This is an example of that false positive.

test1 is indeed inside the string (position 0), but since it returned 0 and your testing it with == TRUE it will go in the else block, leaving out a wrong answer.

So you should always test it !== false:

<?php $_SERVER['HTTP_HOST'] = 'test1.com'; ?>
<?php if(
    (strpos($_SERVER['HTTP_HOST'], 'test1') !== false) OR
    (strpos($_SERVER['HTTP_HOST'], 'test2') !== FALSE)) : ?>
  <p>Do something</p>
<?php else : ?>
  <p>Do something else</p>
<?php endif; ?>

Actually its in the manual covered. Read the red box note.

Upvotes: 2

Related Questions