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 trialDaniel Breen
14,943 PointsHelp understand the order of an array with both associative and non-associative behavior
In the quiz following this video, an associative array exists with a few values. The question asks us to add "orange" as the second value. The answer is
$iceCream[1] = "orange";
When I test this, it shows as the last item in the array. Even more specifically, when I test this using print_r(array_values($iceCream));
, the key for orange is now 3.
I'm coming from JavaScript, so I'm sure I just need some clarification
2 Answers
Micah Walton
4,674 PointsI tested it out and it works as intended. I think you have code somewhere else on the page affected it.
<?php $myList = array("Red", "Blue", "Green", "Yellow", "Purple"); $myList[1] = "Orange"; var_dump($myList); ?>
Returns Orange as the second [1] key of the array.
nico dev
20,364 PointsHi Daniel Breen ,
I imagine your problem is only coming from using array_values
, with which you're effectively returning each value of the array, but only after having such array reindexed. Or, in other words, the array_values will reindex everything starting as always from an index of [0] and so on, and only then it will return the values.
There's more info about it here. Excerpt:
array_values() returns all the values from the array and indexes the array numerically.
By the time array_values returns you the values, it ignores completely the former indices/keys, and only cares about the new ones, assigned numerically and automatically by the function itself.
Hope that clarified it a bit, but if I didn't tackle your real question, feel free to follow up!