Reputation: 187
I'm trying to put a menu together where it will sense what page is loaded. This site is not done in a CMS and is straight PHP/HTML code.
I currently have the navigation working for the primary links. There is a dropdown where I am having problems. I need to be able to see if the parent or any dropdown children are active. If one of the children are active. In the example below this is "FAQ" and the children are "FAQ1," "FAQ2," and "FAQ3."
For this example I'm using a CSS state called "active."
<style>
a{color:red;}
.active{color:blue;}
</style>
Here is the script used for the menu. The links for Home, Products, and Contact are working as expected.
<ul>
<li><a href="index.php" id="homenav" <?php if (strpos($_SERVER['PHP_SELF'], 'index.php')) echo 'class="active"';?>>Home</a></li>
<li><a href="products.php" id ="prodnav" <?php if (strpos($_SERVER['PHP_SELF'], 'products.php')) echo 'class="active"';?>>Products</a></li>
<li><a href="faq.php" id ="faqnav" <?php if (strpos($_SERVER['PHP_SELF'], 'faq.php, faq1.php, faq2.php, faq3.php')) echo 'class="active"';?>>FAQ</a>
<ul>
<li><a href="faq1.php">FAQ1</a></li>
<li><a href="faq2.php">FAQ2</a></li>
<li><a href="faq3.php">FAQ3</a></li>
</ul>
</li>
<li><a href="contact.php" id ="connav" <?php if (strpos($_SERVER['PHP_SELF'], 'contact.php')) echo 'class="active"';?>>contact us</a></li>
</ul>
Can I please get some help on how I should be writing this line to let it work the way the others are?
<li>
<a href="faq.php" id ="faqnav"
<?php
if (strpos($_SERVER['PHP_SELF'], 'faq.php, faq1.php, faq2.php, faq3.php'))
echo 'class="active"';
?>
>FAQ</a>
</li>
Upvotes: 0
Views: 571
Reputation: 824
strpos() only accepts one string per parameter, you can not give it a list. Try this:
<?php if (in_array(basename($_SERVER['PHP_SELF']), array('faq.php', 'faq1.php', 'faq2.php', 'faq3.php'))) echo 'class="active"';?>
basename()
strips the path from the filename, so you only have the pure file namein_array()
then checks if this path is in an arrayarray()
generates an array of strings to be handed over to in_array()
. Note that there are 4 separate strings, not one long one as in your code.Upvotes: 2
Reputation: 91742
If you don't have any other pages that contain faq
, you can simply use:
if (strpos($_SERVER['PHP_SELF'], 'faq') !== false)
Note that I am using !== false
as strpos
can return 0
when faq
is found at the beginning of your string. You should probably use that for your other comparisons too.
Otherwise, go with the in_array
solution of @MrTweek.
Upvotes: 0
Reputation: 2024
Use in_array
for this purpose:
if (in_array($_SERVER['PHP_SELF'], array('faq.php', 'faq1.php', 'faq2.php', 'faq3.php')) echo 'class="active"';
http://php.net/manual/de/function.in-array.php
Upvotes: 0