4

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?

1

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Fabio. If i understand correct i can use $value like i use an array?
@EvgeniyKleban: $value is an array and you are using it as such. Add print_r($value); inside the loop to see the contents of the array on each loop iteration.
@evgeniyKleban Amal is right you can use as array because it is an array
@Fabio are you free atm?
1
foreach ($leftMenu as $key=>$value){
        foreach ($value as $html=>$link){
                if ($html != 'link')    {
                    echo "<a href='{$html}'>{$link}</a>\n";
                }
        }   
    }

This should work.

Comments

1

Try like this:

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

}

demo : https://eval.in/105138

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.