1

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.

0

1 Answer 1

1

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>';
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.