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

Arrays

Hello, im not quite understaind why the result is 01 in this example:

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

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

echo $a;

}```

Why is there index number and not the tititle?

3 Answers

The answer is pretty simple, lets see if I can explain it clearly.

In your function, your array is just a single value. It doesn't have an index [0] => 'Cake Batter, [1] => 'Cookie Dough' or an associative value like 'flavor_one' => 'Cake Batter', 'flavor_two' => 'Cookie Dough'

In your foreach statement though, you are taking each value of your array, and are assigning a key => value pair. Since you don't have a key predefined in your array, PHP is automatically turning your array values into indexed values. Which means it's automatically assigning the key 0 for the first array element, the key 1 for the second element, the key 2 for the third element (because index arrays always start at zero).

The title is stored in variable $b, but you're only asking for it to return variable $a, which contains only the indexed key. You'd want to return $b to get the title.

You're making the reference to $b. Your array is a collection of 'values'.

In your for each loop you are assigning a 'key' to a 'value'. In this case you choose $a as the key and $b as the value. Because your array does not contain keys, PHP by default assigns a key to each value for you.

You can make these variable whatever you want as long as it is a valid PHP variable name.

However, to simplify your foreach statement; you do not necessary need a 'key' => 'value' pair. Your statement could look like

foreach ($flavors as $flavor) {
echo $flavor;
}

and you would get just your flavor names out of your array.

Does that help?

Yes, this first part i understood, my only confusing was in how php knows that $b = title if there isnt nothing making this reference, but i think that php makes this decision, since the index key where first assign to variable "a" so it leaves to one value to assign that is the title, so automatcly php assigns to variable "b", it could be "b" or "c" or other, it wouldnt make diferentes. Am i right?