简体   繁体   中英

In PHP is there a built-in function to replace this foreach loop?

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?

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);

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