longtone Posted January 12, 2010 Share Posted January 12, 2010 I have an associative array eg: array('a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D') I want to be able to move one element to the start, leaving the order of the others unchanged so if I put: $start = 'c'; I would get: array( 'c' => 'C', 'a' => 'A', 'b' => 'B','d' => 'D') Is there a simple way to do this? ( PHP version: 5.2.10 ) Quote Link to comment Share on other sites More sharing options...
thebadbad Posted January 12, 2010 Share Posted January 12, 2010 Not very elegant, but does the job: <?php $array = array('a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D'); $key = 'c'; $val = $array[$key]; unset($array[$key]); $array = array_merge(array($key => $val), $array); //you can also simply add the arrays here instead; array($key => $val) + $array echo '<pre>' . print_r($array, true) . '</pre>'; ?> Quote Link to comment Share on other sites More sharing options...
salathe Posted January 12, 2010 Share Posted January 12, 2010 Here's another way of doing it: $array = array('a' => 'A', 'b' => 'B', 'c' => 'C', 'd' => 'D'); $new = array('c' => $array['c']) + $array; print_r($new); Quote Link to comment Share on other sites More sharing options...
longtone Posted January 13, 2010 Author Share Posted January 13, 2010 Thanks, that's nice and simple Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.