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

Not understanding foreach and keys

Can someone explain what the correct answer is here?

<?php

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

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

    echo $a;

}

?>

1 Answer

Guy Noda-Bailey
Guy Noda-Bailey
18,837 Points

I think it will echo out a list of the keys, ie. [0][1] Let me try it out and get back to you.

Guy Noda-Bailey
Guy Noda-Bailey
18,837 Points

Yep it echoed out the following; 01

In this foreach loop the $a variable is assigned to the Key of the $flavours array! and $b is assigned the Value of that key. Inside the loop it echoes the $a ($flavours Key) each iteration.

I don't think the array in the question has keys.. Isn't it just a normal single dimension array?

Guy Noda-Bailey
Guy Noda-Bailey
18,837 Points

Yeah, in PHP adding a key is optional, when a key isn't specified PHP will automatically assign the increment of the largest previously used integer key. In this case it will assign what we could think of as the index, as a key.

oh of course! Like accessing a single dimensional array by $flavours[n] ! Brain link!