Forum Moderators: coopster

Message Too Old, No Replies

Swapping 2 elements in an associative array?

         

NooK

9:53 am on Feb 28, 2008 (gmt 0)

10+ Year Member



An associative array uses strings as keys, yet obviously PHP has a way of ordering them since if I just do a print_r or if I traverse in it,i the elements will be traversed in the order I put them in.

I need to swap 2 elements in an associative array (Both key and it's respective value need to swap places in the array) yet I can't find a way for PHP to allow me to do something like

$array[0] = $array[1]

since it is an associative array and numerical indexes dont exist.

How do I tackle this problem?

An example would be:


$array = array("banana"=>"yellow","apple"=>"red","kiwi"=>"green","blueberry"=>"blue");

swapFunction($array,"apple","kiwi");

print_r($array);

//The above results in array("banana"=>"yellow","kiwi"=>"green","apple"=>"red","blueberry"=>"blue")

As you might notice from the example above the reason for such a swap if for pure sorting purposes (And as the array will be used to show a table in HTML it needs to be sorted according to what the user chooses).

whoisgregg

2:59 pm on Feb 28, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Take a look at array_splice [php.net] and array_slice [php.net]. :)

Nutter

3:06 pm on Feb 28, 2008 (gmt 0)

10+ Year Member



I've done something similar, but I can't find it in my notes right now so this is close but may not be exact...


function arraySwap($arr, $src, $dst)
{
$tmp = arr[$dst];
$arr[$dst] = $arr[$src];
$arr[$src] = $tmp;
return $arr;
}

NooK

8:38 am on Feb 29, 2008 (gmt 0)

10+ Year Member



Thanks whoisgregg, I have in fact looked at those fuctions however traversing the array has been my problem as I can't find a way to do the swap by using numerical indexes and such although I suppose I could build a new array and return the new array instead, I'll lok at it.

Nutter, thanks for the example but the one you mention swaps the values in between 2 keys which is I dont want to do. I want the keys to hold their values, just swap places.