Page 1 of 1

Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 1:38 pm
by yele
Hi guys, supose I have an an asosciative array, and I need to move the last element of this array from the last position to de first, for example:

$options = array (key1 => A, key2 => B,....., keyn => Z), suposing that que keys doesn´t have an order, I just want to move the last key - value pair from the last pos to the first.

keyn => Z, key1 => A, key2 => B, ......, keyn-1 => Y, something like that.

Could anyone tell me how can I do that?


Thanks in advance, yele.

Re: Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 1:41 pm
by jayshields
Look at array_pop() and array_push().

Re: Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 1:43 pm
by Rebel7284
array_pop followed by array_unshift is probably a better order. :)

Re: Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 2:25 pm
by yele
Rebel7284 wrote:array_pop followed by array_unshift is probably a better order. :)
I use array_unshift like this : array_unshift($options, "0" =>
"----------");

But it gives me an error, something about the arrow, can I insert a pair
key-value with array_unshift??

Re: Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 2:55 pm
by requinix
array_pop/push/shift/unshift don't let you manage keys. Just values.

Code: Select all

$array = array(1 => "one", 10 => "ten", "i" => "eye", ":)" => "happy face");
$array = array_slice($array, -1, 1, true) + array_slice($array, 0, count($array) - 1, true);
print_r($array);

Re: Changing the position of an element in an associative array

Posted: Tue Oct 21, 2008 4:07 pm
by yele
tasairis wrote:array_pop/push/shift/unshift don't let you manage keys. Just values.

Code: Select all

$array = array(1 => "one", 10 => "ten", "i" => "eye", ":)" => "happy face");
$array = array_slice($array, -1, 1, true) + array_slice($array, 0, count($array) - 1, true);
print_r($array);
Great!! It works perfect por me this way, thanks.