0

In order to integrate icons into the navbar I use key=>value arrays to store a file name with an icon tag. In the navbar I use a foreach loop to build dropdown menus or index into an array for an individual navlink. This also allows to dynamically build and alter the dropdown menus very easily.

$homepage = array(
  'index.php'=>'<i class="fa fa-home"></i>'
);
$guestpages = array(
  'createaccount.php'=>'<i class="fa fa-university"></i>',
  'login.php'=>'<i class="fa fa-sign-in"></i>'
);
$logout = array(
  'logout.php'=>'<i class="fa fa-sign-out"></i>'
);
$pages = array($homepage,$guestpages,$logout);

I also parse the URL to determine what page the client is viewing.

$pagename = basename($_SERVER['PHP_SELF']);

And in order to associate the parsed URL with the appropriate icon tag from the $pages array, I currently use a nested foreach loop:

foreach ($pages as $pagearray) {
  foreach ($pagearray as $page => $icon) {
    if($pagename == $page) {
      $pageicon = $icon;
    }
  }
}

And what I'd like to do instead is something like this:

$pageicon = $pages[?][$pagename];

Does a similar alternative solution exist?

1
  • Why the three separate arrays? If you'd just have $pages = ['index.php' => ...], you could simply do $pages[basename($_SERVER['PHP_SELF'])] Commented Nov 13, 2018 at 1:44

1 Answer 1

3

Since your pagename must be unique, you can build your array in a single dimension, like this:

$pages = [
    'index.php'=>'<i class="fa fa-home"></i>',
    'createaccount.php'=>'<i class="fa fa-university"></i>',
    'login.php'=>'<i class="fa fa-sign-in"></i>',
    'logout.php'=>'<i class="fa fa-sign-out"></i>',
];

Then just use:

$icon = $pages[basename($_SERVER['PHP_SELF'])] ?? '<some default>';

[Edit] Alternatively, you can use array_merge() to combine your arrays:

$pages = array_merge($homepage, $guestpages, $logout);
Sign up to request clarification or add additional context in comments.

2 Comments

This would complicate the navbar construction though, because index.php and logout.php are individual links while createaccount.php and login.php are both in the same dropdown menu. So on the navbar I use a loop: foreach($guestpages as...) to build the dropdown menu containing the links to createaccount.php and login.php. I wouldn't be able to create individual dropdown menus from the $pages array, and don't want to maintain a seperate $pages array that is not nested.
Then just use array_merge() to combine them.

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.