Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access array elements using foreach

Tags:

arrays

php

I'm studying php and now I'm struggling in following: i have an array that contains other array like this:

$leftMenu = array(
    array('link'=>'Домой', 'href'=>'index.php'),
    array('link'=>'О нас', 'href'=>'about.php'),
    array('link'=>'Контакты', 'href'=>'contact.php'),
    array('link'=>'Таблицы умножения', 'href'=>'table.php'),
    array('link'=>'Калькулятор', 'href'=>'calc.php')                
);

What i need to do, is draw a menu with hyperlinks by html and this array, using foreach. That is what i tried to do:

foreach ($leftMenu as $key=>$value){
    foreach ($value as $html=>$link){
        echo "<a href=$html>$link </a>\n"; 
    }   
}

Obviously it doesn't work because i get invalid values in variable $link. What i want to, is pass only links to that variable, not text. How to achieve that?

like image 908
Evgeniy Kleban Avatar asked Dec 20 '22 17:12

Evgeniy Kleban


1 Answers

You don't need to loop twice in your array but once

foreach ($leftMenu as $value){
    echo '<a href="'.$value['href'].'">'.$value['link'].'</a>'."\n";   
}

Live working sample here

like image 85
Fabio Avatar answered Dec 24 '22 00:12

Fabio