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 PHP Arrays and Control Structures PHP Loops For Loops

Nicolai Simonsen
Nicolai Simonsen
4,600 Points

Explanation for displaying values and not array keys through loop?

Hi,

When writing the following code as taught by Alena,

$learn = array('Conditionals','Arrays','Loops');
$learn[] = 'Build something awesome';
array_push($learn,'Functions','Forms','Objects');
array_unshift($learn, 'HTML', 'CSS');
asort($learn);

for ($i = 0; $i < count($learn); $i++){
    echo $learn[$i] . "\n";
}

I don't get how the values in the $learn array gets displayed and not the keys? $learn[$i] would be equal to $learn[0] or $learn[1] etc, right?

Nicolai Simonsen
Nicolai Simonsen
4,600 Points

... dang it. Just var_dumped $learn[1] and got the value - which is what happens in the loop? Well that kinda makes sense :)

Jennifer Nordell
seal-mask
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi! I see you answered your own question :thumbsup: But to make it a little clearer, in a non-associative array you can think of the "key" as being the "index". The big difference is that in an associative array, you get to name the keys yourself. So what it's doing is pulling the value from that array at that index(key). Hope that makes sense! :sparkles:

Amr Aly
Amr Aly
5,201 Points

the $learn array is indexed [ 0 => 'HTML', 1 => 'CSS', 2 => 'Conditionals', etc ] $i is 0 , 1 , 2 etc until the count of the element(s) of array is met .

so in the for loop we replace the original index with that $i variable.

Nicolai Simonsen
Nicolai Simonsen
4,600 Points

Hi Jennifer,

Thank you so much! - it makes total sense now. ? Think I need to be more clear on what I'm doing while coding.

Brace yourself for the biggest high-five of them all...

✋!!!

Nicolai Simonsen
Nicolai Simonsen
4,600 Points

Thanks Amr for helping me out! ?