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 & 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>
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.
Use urldecode:
$subpage = urldecode($_GET['subp']);
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:
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