user2220653
user2220653

Reputation: 1

Displaying text via foreach loop php

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

Answers (1)

lfk
lfk

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

Related Questions