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 trialAndrew Dickens
18,352 PointsTurn $key into an array
I want to asort() the keys in my associate array and echo them
I thought I'd use while/list/each to get the keys, put them into an array and then asort() that? Maybe I'm going the wrong way about it but any ideas how to do this?
$animals = array(
'tiger' => '4 legs',
'dolphin' => '0 legs',
'ostrich' => '2 legs',
'elephant' => '4 legs',
'buffalo' => '4 legs',
"hawk" => '2 legs'
);
while (list($key, $val) = each($animals)) {
###turn $key into an array #####
$key_array = ######;
asort($key_array);
echo $key_array;
}
2 Answers
Andrew Dickens
18,352 PointsI guess the question is in the title, how to turn the keys into an array, don't think about the functions on arrays. I want to turn the original array into an array that looks like this array=(tiger, dolphin, ostrich, elephant, buffalo, hawk );
Algirdas Lalys
9,389 PointsHmm, maybe this will do it.
foreach($animals as $key => $animal) {
$animals[] = $key;
// delete old values of assiociative array
unset($animals[$key]);
}
var_dump($animals);
Algirdas Lalys
9,389 PointsAlgirdas Lalys
9,389 PointsHi Andrew,
Could you tell me more what sorted array you would like to be, I didn't understood. There are a few functions for arrays. For example if you want to sort by keys you should use ksort($animals) and the output would be.
and if you need sorted by value then you can use asort($animals) and the output would be.
And of course there are plenty more functions on arrays.