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!

PHP:
function displayNav($i) {
    global $nav_home, $nav_cont, $nav_docs, $nav_prod;
    global $logo_small;

    $active = "class='active'";

    if ($i == 1) { // home
        print("<a " . $active . " href=" . $nav_home . ">Home</a>");
    }
    else {
        print("<a " . " href=" . $nav_home . ">Home</a>");
    }

    if ($i == 2) { // contact
        print("<a " . $active . " href=" . $nav_cont . ">Contact</a>");
    }
    else {
        print("<a href=" . $nav_cont . ">Contact</a>");
    }

    print("<div id='logo'><img src='$logo_small'" . "width='65' /></div>");

    if ($i == 3) { // docs
        print("<a " . $active . " href=" . $nav_docs . ">Docs</a>");
    }
    else {
        print("<a href=" . $nav_docs . ">Docs</a>");
    }
    
    if ($i == 4) { // prods
        print("<a " . $active . " href=" . $nav_prod . ">Products</a>");
    }
    else {
        print("<a href=" . $nav_prod . ">Products</a>");
    }
}


Thank you.
 

Attachments

Last edited by a moderator:
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