user1853105
user1853105

Reputation:

My foreach only finds the last element of the array

This is my first time here. I have a problem with my foreach loop, it only outputs the "Contact Us" link and none of the others.

I can't see a problem with my syntax:

<?php
echo '<nav id="main_nav">';
    $links = array(
        '#' => 'Home',
        '#' => 'About Us',
        '#' => 'Our Services',
        '#' => 'Portfolio',
        '#' => 'Testimonials',
        '#' => 'Gallery',
        '#' => 'Contact Us'
    );
    foreach($links as $href => $label){
        echo '<a href="',$href,'">',$label,'</a>';
    }
    echo '</nav>';
?>

Upvotes: 4

Views: 3679

Answers (4)

som
som

Reputation: 4656

Beacuse your array key indexes are same. that is why it print only Contact Us

print_r( $links );

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 4305

That is becuase of same index elements in your array........

<?php
echo '<nav id="main_nav">';
$links = array(
    '0' => 'Home',
    '1' => 'About Us',
    '2' => 'Our Services',
    '3' => 'Portfolio',
    '4' => 'Testimonials',
    '5' => 'Gallery',
    '6' => 'Contact Us'
);
foreach($links as $href => $label){
    echo '<a href="',$href,'">',$label,'</a>';
}
echo '</nav>';

?>

and the answer is <nav id="main_nav"><a href="0">Home</a><a href="1">About Us</a><a href="2">Our Services</a><a href="3">Portfolio</a><a href="4">Testimonials</a><a href="5">Gallery</a><a href="6">Contact Us</a></nav>

Upvotes: 2

ka_lin
ka_lin

Reputation: 9432

change to echo '<a href='#'>'.$label.'</a>'; and change the keys and add # by hand, for string concatenation use the dot

Upvotes: 0

zerkms
zerkms

Reputation: 254896

That's because you should specify different keys for the elements in your array.

var_dump($links); and see your array consists of a single element.

http://ideone.com/epstaT

Upvotes: 3

Related Questions