Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Build a Simple PHP Application Listing Inventory Items Nesting Arrays Within Arrays

Darrel Lyons
Darrel Lyons
2,991 Points

Foreach loop not working

Why is the foreach loop only showing the last array?

PHP:

<?php

$vehicles = array();
$vehicles[101] = array(
    "car" => "viper",
    "price" => "500000",
        "get" => "viper"

);
$vehicles[102] = array(
    "car" => "Lamborghini Murcielago",
    "price" => "600000",
    "get" => "murc"
);

?>

HTML:

<?php foreach($vehicles as $vehicle); { ?>
    <h1><?php echo $vehicle["car"]; ?></h1>
    <?php } ?>

2 Answers

Look again this line : <?php foreach($vehicles as $vehicle); { ?> after $vehicle) you are adding a semicolon but it is a mistake. Delete that semicolon and everything will be fine.

Darrel Lyons
Darrel Lyons
2,991 Points

Silly me! Thank you! :)

Justin Ellingwood
Justin Ellingwood
12,545 Points

Hey Darrel,

It looks like you have a stray semi-colon after your foreach parentheses before the opening bracket.

I think you should get what you're looking for if you remove it so that it looks like this:

<?php foreach($vehicles as $vehicle) { ?>
    <h1><?php echo $vehicle["car"]; ?></h1>
<?php } ?>

Edit: beaten to it! :) Glad you got some help!

Darrel Lyons
Darrel Lyons
2,991 Points

I watched the video many times and i was looking back at my script thinking what have i done wrong. Such a silly error that i didn't see.. thanks for your reply! :)