N
N
ne_mo2015-10-24 13:52:17
PHP
ne_mo, 2015-10-24 13:52:17

How to assign the .active class to the first element of an array using a foreach loop?

Detailed, I have a multidimensional array this is a navigation menu

$menu = [
    ['link'=>'Домой', 'href'=>'index.php'],
    ['link'=>'Новости', 'href'=>'news.php'],
    ['link'=>'Оплатить', 'href'=>'pay.php'],
    ['link'=>'О нас', 'href'=>'about.php'],
    ['link'=>'Контакты', 'href'=>'contact.php']
];

I output it through a foreach loop
foreach($menu as $val){
    echo "<li> <a href={$val['href']}>{$val['link']}</a> </li>";
}

But I want to prescribe that the first element, the main page, was assigned the .active class to assign the css of the active page.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
wol_fi, 2015-10-24
@ne_mo

Well, if it's simple, then you can do it like this:

$first = true;
foreach($menu as $val){
    echo "<li " . ($first ? ' class="active"' : '') . "> <a href={$val['href']}>{$val['link']}</a> </li>";
    if ($first) {
       $first = false;
    }
}

Or like this:
foreach($menu as $val){
    echo "<li " . ($menu[0]['href'] == $val['href'] ? ' class="active"' : '') . "> <a href={$val['href']}>{$val['link']}</a> </li>";
}

S
Sergey Ivchenko, 2015-10-24
@Serg89

<?php foreach ($menu as $key => $value) : ?>
  <li <?if (!$key) :?>class="active"<?php endif;?>><a href={$val['href']}>{$val['link']}</a></li>
<?php endforeach ;?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question