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 ) Link to comment https://forums.phpfreaks.com/topic/188187-how-to-move-one-element-of-array-to-start/ 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>'; ?> Link to comment https://forums.phpfreaks.com/topic/188187-how-to-move-one-element-of-array-to-start/#findComment-993491 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); Link to comment https://forums.phpfreaks.com/topic/188187-how-to-move-one-element-of-array-to-start/#findComment-993507 Share on other sites More sharing options...
longtone Posted January 13, 2010 Author Share Posted January 13, 2010 Thanks, that's nice and simple Link to comment https://forums.phpfreaks.com/topic/188187-how-to-move-one-element-of-array-to-start/#findComment-993964 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.