How add active state to the navigation menu with php

<div id="nav">
                <li class="item"><a href="/">Home</a>/</li>
                <li class="item"><a href="/two">Tab2</a></li>
                <li class="item"><a href="/three">Tab3</a></li>
                 <li class="item"><a href="/four">Tab3</a></li>

IF I want to add the class=“active” to a label, like this

 <li class="item"><a href="" class="active">Home</a>/</li>

. how should i do?i got this, but it’s too complicated. is there a simple way to get it ? thank you.

$current = array("","two","three","four");
<li class="item"><a href="/$current[0]" class="<?php if($GET[$current[0]=="") echo "active"; ?>">Home</a>/</li>
 <li class="item"><a href="/$current[1]" class="<?php if($GET[$current[1]]=="two") echo "active"; ?>">Tab2</a></li>
     <li class="item"><a href="/$current[2]" class="<?php if($GET[$current[2]]=="three") echo "active"; ?>">Tab3</a></li>
      <li class="item"><a href="/$current[3]" class="<?php if($GET[$current[3]]=="four") echo "active"; ?>">Tab3</a></li>

is the code that wrote by me right?

Why don’t you add the class directly in the HTML? Depending on the page you are in, you can add the active class to the correct link and you wouldn’t need to use any scripts.

Edit: I’ve just realized that maybe you want to use GET requests, but it doesn’t look like you are having any parameters in your URL.

You code has some syntax errors, by the way:

$current = array(1 => '', 2 => 'two', 3 => 'three', 4 => 'four');



instead of


And some others, like unbalanced parentheses.

Maybe it’s better if you tell us what you are trying to accomplish here with your code, so that it’s easier for us to help you.

Edit 2: I forgot to add the last part :smiley: The best way in this case is to probably use Javascript. Have a look at this article, maybe it’s what you are looking for:

many thanks. i want to add class=‘active’ to the menu. when the menu is the current page.namely. when i on the home page. the a label is

<li class=“item”><a href=“/” class=“active”>Home</a>/</li>
.but the others a label are not have class=“active”. when i on the Tab2 page. it is is
<li class=“item”><a href=“two” class=“active”>tab2</a>/</li>
.the others a label are not have class=“active”.

#3 { visibility: inherit; } Highlight Current Page Plus!

You were somehow on the right direction :slight_smile:

Point 3 in this article does what you were trying to do :wink:

Try this:

			.active { color: red; }

		$current = array(
			"" => "Home",
			"two" => "Tab2",
			"three" => "Tab3",
			"four" => "Tab4"
		foreach( $current as $k => $v ) {
			$active = $_GET['page'] == $k
				? ' class="active"'
				: '';
			echo '<li class="item"><a href="/'. $k .'"'. $active .'>'. $v .'</a></li>';