Changing the position of an element in an associative array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yele
Forum Newbie
Posts: 5
Joined: Tue Oct 21, 2008 1:28 pm

Changing the position of an element in an associative array

Post 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.
User avatar
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

Post by jayshields »

Look at array_pop() and array_push().
Rebel7284
Forum Newbie
Posts: 7
Joined: Mon Oct 20, 2008 2:59 pm

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

Post by Rebel7284 »

array_pop followed by array_unshift is probably a better order. :)
yele
Forum Newbie
Posts: 5
Joined: Tue Oct 21, 2008 1:28 pm

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

Post 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??
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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);
yele
Forum Newbie
Posts: 5
Joined: Tue Oct 21, 2008 1:28 pm

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

Post 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.
Post Reply