Enhance the Efficiency of my Function

katiemac

New member
I've created a PHP function named displayNav($i) and pass it the variable $i.

This function is responsible for rendering a navigation bar at the top of my web pages.

I want to apply the active class to the appropriate href tag based on the page the user is currently on,
as illustrated in the attached file.

I feel there is a more efficient way to do this, but I'm having trouble finding a better solution.

Any advice would be greatly appreciated!

Thank you.
 

Attachments

  • function.txt
    971 bytes · Views: 2
A more efficient way to do this would be to use an array to store the navigation items and their corresponding values. Then, you can loop through the array and check the value of $i only once for each item.

PHP:
function displayNav($i) {
global $logo_small;
$navItems = array(
1 => "Home",
2 => "Contact",
3 => "Docs",
4 => "Products"
);
foreach ($navItems as $key => $value) {
$active = ($i == $key) ? "class='active'" : "";
echo "<a href='#' $active>$value</a>";
}
}
 
Back
Top