phparrayssortingassociative-array

Move an element by key before another element by key in the context of an associative array


In PHP, I would like to have the ability to re-order an associative array by moving elements to certain positions in the array. Not necessary a sort, just a re-ordering of my choosing.

As an example, say I have an associative array as follows:

array(
 'a' => 'Element A',
 'b' => 'Element B',
 'c' => 'Element C',
);

and in one case i may want to move C before B and have the following result:

array(
 'a' => 'Element A',
 'c' => 'Element C',
 'b' => 'Element B',
);

or in another case i may want to move C before A and have the following result:

array(
 'c' => 'Element C',
 'a' => 'Element A',
 'b' => 'Element B',
);

What I am trying to show, is simply a method for saying "Hey, I want to move this array element before this other array element" or "Hey, id like to move this array element to make sure that it comes after this other array element'


Solution

  • If you mean to swap two values you could make a function like this:

    function array_swap($key1, $key2, $array) {
            $newArray = array ();
            foreach ($array as $key => $value) {
                if ($key == $key1) {
                    $newArray[$key2] = $array[$key2];
                } elseif ($key == $key2) {
                    $newArray[$key1] = $array[$key1];
                } else {
                    $newArray[$key] = $value;
                }
            }
            return $newArray;
        }