1

I am trying to create a subnav that echos "current" when the script finds itself on the appropriate page and subpage.

My issue is that when $subpage == $encoded_subpage_name?"current":"" is compared, subnav names with spaces always equal false because $encoded_subpage_name will have a + but $subpage won't.

<?php

    if (isset($_GET['p'])) {
        $page = $_GET['p'];
    } else {
        $page = "";
    }
    if (isset($_GET['subp'])) {
        $subpage = $_GET['subp'];
    } else {
        $subpage = "";
    }

    $subpages = array(
        "powered by company",
        "text messaging",
        "the app",
        "NFC",
        "your membership",
        "faq",
        "privacy policy",
        "terms &amp; conditions"
    );


    function buildSubNav($page, $subpages) {
        foreach ($subpages as $subpage) {
            $encoded_subpage_name = urlencode($subpage);
            echo '<li class="' . selected_subpage($encoded_subpage_name) . '"><a href="?p=' . $page . '&subp=' . $encoded_subpage_name . '"> ' . $subpage . '</a></li>';
        }
    }
    function selected_subpage($encoded_subpage_name) {
        global $subpage;
        $subpage = ($subpage);
        echo $subpage;
        return $subpage == $encoded_subpage_name?"current":"";
    }


?>
<ul>
    <?php buildSubNav($page, $subpages); ?>
</ul>
nipponese
  • 2,813
  • 6
  • 35
  • 51

3 Answers3

3

The problem you're having is that you're encoding in the middle of your work instead of at the end when you're actually outputting. Stop doing that.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

Use urldecode:

$subpage = urldecode($_GET['subp']);
Yan Berk
  • 14,328
  • 9
  • 55
  • 52
1

I would recommend that you change your page names in the code to URL-friendly names (like most CMSes does with their permalinks), then the string will stay the same after you have URL-encoded it.

Something in style with:

  • Replace space with -
  • Replace "&" with "and"
  • Replace international characters such as ÅÄÖ with similar ones AAO
  • Remove all characters that doesn't match alphabetic/numberic characters and "-"

That would in your case generate something like:

$subpages = array(
    "powered-by-company",
    "text-messaging",
    "the-app",
    "NFC",
    "your-membership",
    "faq",
    "privacy-policy",
    "terms-and-conditions"
);

Links that might be interesting

Community
  • 1
  • 1
Robin Andersson
  • 5,150
  • 3
  • 25
  • 44