0

I'm matching a set of strings against a string and if one of the strings of the array appears in the string, then some text should show up.

In practice: I would like to include a menu only on specific pages. So I include a PHP snippet in my template and the menu should show up when one of the defined page names appears in the URL. Currently I use this code which works:

$domain = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];

if (strpos($domain, '/page1.php') !== false) {
        echo 'Text',
}
elseif (strpos($domain, '/page2.php') !== false) {
        echo 'Text',
}
elseif (strpos($domain, '/page3.php') !== false) {
        echo 'Text',
}
elseif (strpos($domain, '/page4.php') !== false) {
        echo 'Text',
};

Is it possible to condense the code to make it more efficient rather than repeating for each page an elseif line. I tried the following but it didn't work:

$domain = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];
$string = array('page1.php', 'page2.php', 'page3.php', 'page4.php');

if (strpos($domain, $string) !== false) {
        echo 'Text',
};

Any suggestions?

Philip

3 Answers 3

2
$domain = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];
$string = array('page1.php', 'page2.php', 'page3.php', 'page4.php');
foreach($string as $str){
   if (strpos($domain, $str) !== false) {
    echo 'Text',
   }
}
Sign up to request clarification or add additional context in comments.

Comments

0

If each page has to generate a different results then you should use switch(), and if all the results are the same then just create an array('page1.php', 'page2.php', 'page3.php', 'page4.php'); and use in_array() ...

Comments

0

try this,

$domain = $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING'];
$string = array('page1.php', 'page2.php', 'page3.php', 'page4.php');

foreach ($string as $key => $value) {
  if (strpos($domain, $value) !== false) {
    echo 'Text',
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.