Switch two items in associative array

后端 未结 17 1898
自闭症患者
自闭症患者 2021-02-05 12:53

Example:

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


        
17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-05 13:00

    I'll share my short version too, it works with both numeric and associative arrays.

    array array_swap ( array $array , mixed $key1 , mixed $key2 [, bool $preserve_keys = FALSE [, bool $strict = FALSE ]] )
    

    Returns a new array with the two elements swapped. It preserve original keys if specified. Return FALSE if keys are not found.

    function array_swap(array $array, $key1, $key2, $preserve_keys = false, $strict = false) {
        $keys = array_keys($array);
        if(!array_key_exists($key1, $array) || !array_key_exists($key2, $array)) return false;
        if(($index1 = array_search($key1, $keys, $strict)) === false) return false;
        if(($index2 = array_search($key2, $keys, $strict)) === false) return false;
        if(!$preserve_keys) list($keys[$index1], $keys[$index2]) = array($key2, $key1);
        list($array[$key1], $array[$key2]) = array($array[$key2], $array[$key1]);
        return array_combine($keys, array_values($array));
    }
    

    For example:

    $arr = array_swap($arr, 'grapefruit', 'pear');
    

提交回复
热议问题