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.
Changing the position of an element in an associative array
Moderator: General Moderators
- jayshields
- DevNet Resident
- Posts: 1912
- Joined: Mon Aug 22, 2005 12:11 pm
- Location: Leeds/Manchester, England
Re: Changing the position of an element in an associative array
Look at array_pop() and array_push().
Re: Changing the position of an element in an associative array
array_pop followed by array_unshift is probably a better order. 
Re: Changing the position of an element in an associative array
I use array_unshift like this : array_unshift($options, "0" =>Rebel7284 wrote:array_pop followed by array_unshift is probably a better order.
"----------");
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
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
Great!! It works perfect por me this way, thanks.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);