简体   繁体   中英

Displaying all list items while using a foreach loop in php

I need some assistance to create a foreach loop which will display each array item from an array with three items. Currently, my code correctly displays the first and last item; however, it does not display the second item.

The loop will be used to generate a navbar from the items in the array.

Here is my PHP code:

<ul>
<?php
    $navOptions = array('home','services','contact');

    foreach($navOptions AS $navOption) {
        if ($navOption == $currentPage) {
            echo '<li><a href ="' . $navOption . '.php class="current">' . ucfirst($navOption) . '</li></a>';
        } else {
            echo '<li><a href="' . $navOption . '.php>' . ucfirst($navOption) . '</li></a';
        }

    }
?>
</ul>

This code generates a list of links like this:

  • Home
  • Contact

However, it does not generate the "Services" list item.

A side note: the $currentPage variable is declared as a global variable on each individual html page ie, within index.php, services.php, contact.php.

You are missing some double quotes, and the closing > of the else statement, should be as follows:

$navOptions = array('home','services','contact');

    foreach($navOptions AS $navOption) {
        if ($navOption == $currentPage) {
            echo '<li><a href="' . $navOption . '.php" class="current">' . ucfirst($navOption) . '</li></a>';
        } else {
            echo '<li><a href="' . $navOption . '.php">' . ucfirst($navOption) . '</li></a>';
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM