Syarif
Syarif

Reputation: 23

Multidimensional Array PHP in CSS

I have a problem in my web app.

I'd like to make a menu, when menu clicked it'll be active in css.

Code below is my index.php

<?php
    include 'menu.php';
    $page = $_GET['page'];
    switch ($page) {
      case 'endCart':
        include 'endCart.php';
        break;

      case 'trxLog':
        include 'invoice.php';
        break;

      case 'graph':
        include 'graph.php';
        break;

      case 'activeBasket':
        include 'activeBasket.php';
        break;

      case 'logout':
        include 'logout.php';
        break;

      default:
        include 'endCart.php';
        break;
    }

?>

And code below is menu.php

<div class="column" id="sidebar">
  <div class="ui secondary vertical fluid menu">

    <?php

    foreach($sidemenu as $arr){
      echo '<a class="item" href="'.$arr[1].'">'.$arr[0].'</a>';
    }

    ?>
  </div>
</div>

I get variable $sidemenu from array with value below :

$sidemenu = array(
    array('End Cart','index.php?page=endCart', 'endCart'),
    array('Transaction Log','index.php?page=trxLog', 'trxLog'),
    array('Graph','index.php?page=graph', 'graph'),
    array('Active Basket','index.php?page=activeBasket', 'activeBasket')
);

As writen in file menu.php, there is tag <a> with item in its CSS class.

So my problem is when user clicked specific menu in that tag will append CSS class active.

Update!!

This problem has been solved, and here it is my update for menu.php. Big thanks for @Magnus and @Steve to help me solve this.

foreach($sidemenu as $arr){
  echo ($page == $arr[2]) ? "<a class=\"item active\" href=\"".$arr[1]."\">".$arr[0]."</a>" : "<a class=\"item\" href=\"".$arr[1]."\">".$arr[0]."</a>";
}

Upvotes: 0

Views: 251

Answers (1)

M. Eriksson
M. Eriksson

Reputation: 13635

First, change the order of the page and menu include. That way, $page will be available in your menu.php-file:

// I also added a check to see if that query string exists
$page = isset($_GET['page']) ? $_GET['page'] : '';
include 'menu.php';

In your menu.php, just check if the loop is printing the current url:

foreach($sidemenu as $arr){
    echo '<a class="item ' . $arr[2] == $page ? "active" : null . '" href="'.$arr[1].'">'.$arr[0].'</a>';
}

This will give the current page link the class active.

Edit

I totally missed that $arr[2] already contains the page key. You don't need to build the url to compare it, as I did in my first example. Thanks @steve for pointing that out.

Upvotes: 2

Related Questions