Answer the question
In order to leave comments, you need to log in
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']
];
foreach($menu as $val){
echo "<li> <a href={$val['href']}>{$val['link']}</a> </li>";
}
Answer the question
In order to leave comments, you need to log in
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;
}
}
foreach($menu as $val){
echo "<li " . ($menu[0]['href'] == $val['href'] ? ' class="active"' : '') . "> <a href={$val['href']}>{$val['link']}</a> </li>";
}
<?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 questionAsk a Question
731 491 924 answers to any question