Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the most elegant way to rearrange an associative array?

Tags:

arrays

php

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)?

like image 480
Fletcher Moore Avatar asked Apr 22 '10 20:04

Fletcher Moore


2 Answers

$hash = array('Car' => 'Ford') + $hash;
like image 56
zerkms Avatar answered Sep 29 '22 01:09

zerkms


ksort() ?

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

like image 20
Matteo Riva Avatar answered Sep 29 '22 02:09

Matteo Riva