Reputation: 1
I am trying to make a nav bar for a website. I have to use a foreach loop to display the different pages. However, whenever I try to display them they do not link the pages and they show the wrong text.. Here is the code:
<?php
//Main Navigation Function
function main_nav(){
$nav_sections = array("home"=>"","products"=>"products/","services"=>"services/",
"about"=>"about/", "contact"=>"contact/");
$output = "<UL>";
$i=0;
foreach($nav_sections as $nav){
$output .= "<LI><A href=" . URL_ROOT . $nav . "></A>" . $nav . "</LI>";
}
echo $output;
}
?>
URL_ROOT is a constant defined that gives the root URL, however it is not linking the pages through the text. This is what the site currently displays: http://tomcat.cit.iupui.edu/gaddough/cit21500/assignment4/
Upvotes: 0
Views: 426
Reputation: 498
You've (correctly) set up your array as key-value pairs, meaning you'll have to loop through it as such:
foreach($nav_sections as $title => $link) {
$output .= "<li><a href=" . URL_ROOT . $link . ">" . ucfirst($title) . "</a></li>" . PHP_EOL;
}
ucfirst()
makes the first letter of the word or sentence uppercase.
Furthermore, in your current loop you open and close the anchor (link) without assigning any text to it (i.e. there's nothing between <a href...>
and </a>
.
Last points: you'll want to echo the $output
either between <ul>
or <ol>
tags, and your counter $i
is superfluous in this particular snippet.
Upvotes: 1