user7349906
user7349906

Reputation:

PHP: How can I check which navbar point is active?

I have to check which listpoint in the menu is active and I'd like to know if there's a way in php?

<ul class="menu">
  <li class="a">...</li>
  <li class="b">...</li>
  <li class="c">...</li>
</ul>

So how can I check if a is active or b or c, etc. ?

In my example I mean, how can I give the <li> which you selected a class="...", but only this one.

Upvotes: 0

Views: 80

Answers (2)

GrumpyCrouton
GrumpyCrouton

Reputation: 8621

In a pinch you can get this done with php sessions, simply set a variable any time a menu is switched.

The session variable should be set near the top of whatever page it is being used on, so that way PHP can recognize it before the menu loads on the page.

Here is a small snippet for inspiration, you could do this a lot of different ways.

<?
session_start();

if(isSet($_GET['switch'])) {
    $_SESSION['menuPage'] = $_GET['switch'];
}
$menuPage = $_SESSION['menuPage'];

echo $menuPage."<br>";

?>

<ul class="menu">
    <li <? if(strcmp($menuPage,"a") == 0) { echo "active"; } ?> class="a"><a href="?switch=a">A</a></li>
    <li <? if(strcmp($menuPage,"b") == 0) { echo "active"; } ?> class="b"><a href="?switch=b">B</a></li>
    <li <? if(strcmp($menuPage,"c") == 0) { echo "active"; } ?> class="c"><a href="?switch=c">C</a></li>
</ul>

Note: You want to use a session and not a normal variable so that the $_GET for the menu doesn't have to constantly be present in the URL.

Upvotes: 1

Raf
Raf

Reputation: 113

You may want to look into the $_SERVER variable, more specifically $_SERVER['REQUEST_URI']. This shows you the requested URL. Based on this, you can check which menu item should be active.

Upvotes: 0

Related Questions