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 trialBen Whitehead
5,033 PointsUndefined index??? (Listing Inventory Items code challenge)
Hello - I'm stumped on this code challenge. My foreach loop isn't working for some reason - I get an "Undefined index" error. The first line of the error is below:
Notice: Undefined index: Chocolate in C:\xampp\htdocs\flavors.php on line 25
I wrote a while loop above before the foreach loop to test it out and it worked fine. The code for the code challenge is below, starting with the array declaration:
<?php
$flavors = array();
$flavors[] = "Chocolate";
$flavors[] = "Vanilla";
$flavors[] = "Deliciousness";
$flavor = 0;
while($flavor < 3) {
echo $flavors[$flavor] . "<br>";
$flavor++;
}
?>
<html> <body>
<p>Welcome to Ye Olde Ice Cream Shoppe. We sell <?php echo count($flavors); ?> flavors of ice cream.</p>
<ul>
<?php foreach($flavors as $flavor) { ?>
<li><?php echo $flavors[$flavor] . "\n"; ?></li>
<?php } ?>
</ul>
</body> </html>
I don't know where I went wrong! Can someone show me the light?
Thanks!!
1 Answer
Nick Beatty
9,257 PointsI think it should just be:
<?php echo $flavor . "\n"; ?>
You're currently trying to use "chocolate" as an array index. :)
Ben Whitehead
5,033 PointsBen Whitehead
5,033 PointsThat fixed it! Looks like I was confused on the difference between a foreach loop and the other loops. So in a foreach, you never have to make use of the index? In other words, the actual loop does that for you? Whereas you do have to use the index in the other loops?
Thanks!!!