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 Integrating with PayPal Forms, Arrays, and Get Variables

Titus Ndoka
Titus Ndoka
2,350 Points

Why does this code echo "0" ?

I ran this code, and it echoed a "0". Perhaps I'm just tired, but I still don't get it. Please walk me through what happens:

<?php
$flavors = array("Cake Batter","Cookie Dough");

foreach ($flavors as $a => $b) {

    echo $a;
    exit;

}
?>

2 Answers

Erik McClintock
Erik McClintock
45,783 Points

Titus,

The reason that this particular setup of a foreach is echoing 0 is because it is echoing the key of the value that happens to be at the first position in the array. Let's break this down a little further to help make sense of things:

1) Recall that arrays are "zero-based indexes", so if they have 10 items in them, those items are going to be in index positions (i.e. key positions) 0 - 9, rather than 1 - 10.

2) Recall that arrays are stores of ( key => value ) pairs. In this particular array, you have two ( key => value ) pairs, which are ( 0 => "Cake Batter" ) and ( 1 => "Cookie Dough" ).

3) You are echoing the value of the variable $a, which, when set up in the foreach as "$a => $b", is referencing the index of the item, and thus, will echo the first index it comes across, which is 0.

4) Since we have the "exit" command in our loop, we are forcing it to break prematurely, and it will not finish iterating through the remaining element(s) in our array. As this foreach loop started at the beginning of the array, and was then forced to exit after going over the first item inside it, we will only be printing one item, which is that first index of 0.

Hope this helps to clarify things a bit, and happy coding!

Erik

Titus Ndoka
Titus Ndoka
2,350 Points

Wohoo! I see it now!! Total sense - :-)

Thanks Erik - especially for taking the time to explain it.

Much Obliged!!