Jump to content

How to move one element of array to start?


longtone

Recommended Posts

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 )

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>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.