Showing a menu with buttons with dropdown submenus I have to display a menu where some buttons have dropdown submenus and show if the current button is active or not and put a CSS class to it for each of the two situations (or in both).

&lt;?php

$menus_array = array(
    array('item1', false),
    array('item2', true),
    array('item3', false)
);

$active_item = 'item2';

foreach ($menus_array as $menu_item) {
    if ($menu_item == $active_item &amp;&amp; $menu_item[1] != true) {
        $css_class = ' class="active"';
    } else if ($menu_item != $active_item &amp;&amp; $menu_item[1] == true) {
        $css_class = ' class="dropdown"';
    } else if ($menu_item == $active_item &amp;&amp; $menu_item[1] == true) {
        $css_class = ' class="active dropdown"';
    } else {
        $css_class = '';
    }
}

?&gt;


I've written the code as above, but I don't really like it. Is there a way to write it better? I'm talking about the foreach loop.
A few things first:


$menu_item == $active_item should probably be $menu_item[0] == $active_item
Depending on where that array is coming from, it should probably be associative.  Imagine if you came across the code out of context.  You'd quickly find yourself wondering what in the world menu_item[0] and menu_item[1] are.  menu_item['name'] and menu_item['down'] would be much more descriptive (or something like that).
if (... &amp;&amp; $x == true) {} is identical to if (... &amp;&amp; $x) { }.  Don't include the implicit truth comparison.  The only time you should compare against booleans is if you're wanting to compare type too.  if ($result === false) {}




Anyway, I would probably do something like this:

foreach ($menus_array as $menu_item) {

    $classes = array();

    if ($menu_item[0] == $active_item) {
        $classes[] = 'active';
    }

    if ($menu_item[1]) {
        $classes[] = 'dropdown';
    }

    $css_class = ' class="' . implode(' ', $classes) . '"';

}




Or, if you are into micro-optimizing (and you shouldn't be):

foreach ($menus_array as $menu_item) {

    $class = '';

    if ($menu_item[0] == $active_item) {
        //Could be = instead of .= but putting .= will mean that you
        //can add another assignment above this and not have to change
        //= to .= here.
        $class .= 'active ';
    }

    if ($menu_item[1]) {
        $class .= 'dropdown ';
    }

    $css_class = ' class="' . rtrim($class) . '"';

}


(The rtrim really isn't necessary, but I'm picky. If I were super worried about performance, I would omit the rtrim.)



I would go with the array based one.  Rendering HTML is never going to be your bottleneck, and it's the easier one for me to read.