Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch two items in associative array

Tags:

arrays

php

Example:

$arr = array(
  'apple'      => 'sweet',
  'grapefruit' => 'bitter',
  'pear'       => 'tasty',
  'banana'     => 'yellow'
);

I want to switch the positions of grapefruit and pear, so the array will become

$arr = array(
  'apple'      => 'sweet',
  'pear'       => 'tasty',
  'grapefruit' => 'bitter',
  'banana'     => 'yellow'
)

I know the keys and values of the elements I want to switch, is there an easy way to do this? Or will it require a loop + creating a new array?

Thanks

like image 841
leon.nk Avatar asked Mar 15 '10 15:03

leon.nk


1 Answers

Just a little shorter and less complicated than the solution of arcaneerudite:

<?php
if(!function_exists('array_swap_assoc')) {
    function array_swap_assoc($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;
    }
}

$array = $arrOrig = array(
    'fruit' => 'pear',
    'veg' => 'cucumber',
    'tuber' => 'potato',
    'meat' => 'ham'
);

$newArray = array_swap_assoc('veg', 'tuber', $array);

var_dump($array, $newArray);
?>

Tested and works fine

like image 85
metti Avatar answered Oct 12 '22 22:10

metti