views:

68

answers:

3

Suppose you have an associative array

$hash['Fruit'] = 'Apple';
$hash['Name'] = 'Jeff';
$hash['Car'] = 'Ford';

and you cannot change the order in which these variables are created. So Car is always added to the array after Name, etc. What's the prettiest way to add/move Car to the beginning of the associative array instead of the end (default)?

+2  A: 

ksort() ?

But why would you care about the array's internal order?

kemp
I think he is asking for a push onto the beginning of the array, that's a good hint, though
Jhonny D. Cano -Leftware-
I thought about this but figured with his real data this very indirect solution would not always work.
erisco
In this case, I am going to loop over the array with foreach() later, and for display purposes, I want certain values to appear on top.
Fletcher Moore
+4  A: 
$hash = array('Car' => 'Ford') + $hash;
zerkms
Hey, great minds *do* think alike :D See my answer for the variable version.
erisco
+1  A: 
array_reverse($hash, true);

This is not a very direct solution but one that is:

$value = end($hash);
$hash = array(key($hash) => $value) + $hash;
erisco
yep, i've read this ;-) great way to move item that already was added to an array.
zerkms