Jump to content
Larry Ullman's Book Forums

Ch12- Create A Dynamic Current Class For Header.Html?


Recommended Posts

<nav>

<ul>

<?php

 

$pages = array(

'Home Page' => 'index.php',

'Register' => 'register.php'

 

);

 

$this_page = basename($_SERVER['PHP_SELF']);

 

foreach($pages as $k => $v) {

echo '<li';

if($this_page == $k) {

echo ' class="current"';

echo ' > <a href="'.$v.'"> <span> ' . $k . ' </span> </a> </li> ';

}

}// End of foreach loop

 

?>

 

</ul>

</nav>

Link to comment
Share on other sites

As I told you, echo out $this_page. You'll then see you'll never get a match. You need a way to match that value with something in your pages array. For that to work, you need to be sure you are comparing the right values.

 

You also do a foreach with $k and $v. Lets say index.php is active. That test will check if "front page" is equal to "something in you link structure." You would more likely check $v.

 

Writing from mobile now, so I'm a little limited here.

  • Upvote 1
Link to comment
Share on other sites

<?php
// Assign pages
$pages = array(
 'Home Page' => 'index.php',
 'Register' => 'register.php'
);

// Get the current page
$current = basename($_SERVER['PHP_SELF']);
?>

<nav>
 <ul>
 <?php foreach ( $pages as $desc => $page)
 {
  $active = ($page == $current) ? ' class="current"' : null;
  echo '<li'.$active.'><a href="'.$page.'"><span>'.$desc.'</span></a>'
 }
 ?>
 </ul>
</nav>

Link to comment
Share on other sites

 Share

×
×
  • Create New...