What is the most elegant way to rebuild an associative array?

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, the car is always added to the array after the name, etc. What is the best way to add / move a car to the beginning of an associative array instead of the end (default)?

+5
source share
4 answers
$hash = array('Car' => 'Ford') + $hash;
+8
source

ksort()?

But why bother with the internal order of the array?

+2
source
array_reverse($hash, true);

, :

$value = end($hash);
$hash = array(key($hash) => $value) + $hash;
+1

-

$new_items = array('Car' => 'Ford');
$hash = array_merge($new_items, $hash);

. , (, Id), ....

$new_items = array('Car' => 'Ford','Id'=>'New Id');
$hash = array_merge($new_items, $hash);

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

All Articles