Switch two items in associative array

change order of array php
php swap variables
swapping in 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

There is no easy way, just a loop or a new array definition.

php - Switch two items in associative array, There is no easy way, just a loop or a new array definition. A value can appear more than once in an array. For example, two persons in a list can have the same name but need to have different user IDs. In this article, we will explain how you can declare and initialize associative arrays in Linux bash. We will further elaborate on the power of the associative arrays with the help of various examples.

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

Swapping 2 elements in an associative array?, 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  Click any item in the array. The Array contextual ribbon displays. Click Array tab > Options panel > Replace Item. Select the replacement objects and press Enter. Select the base point for the replacement objects. Select the items in the array to be replaced. Exit the command. In this example, two of the items in the array are replaced by items with larger panes.

Here's my version of the swap function:

function array_swap_assoc(&$array,$k1,$k2) {
  if($k1 === $k2) return;  // Nothing to do

  $keys = array_keys($array);  
  $p1 = array_search($k1, $keys);
  if($p1 === FALSE) return;  // Sanity check...keys must exist

  $p2 = array_search($k2, $keys);
  if($p2 === FALSE) return;

  $keys[$p1] = $k2;  // Swap the keys
  $keys[$p2] = $k1;

  $values = array_values($array); 

  // Swap the values
  list($values[$p1],$values[$p2]) = array($values[$p2],$values[$p1]);

  $array = array_combine($keys, $values);
}

Swap two array elements - TeX, Last note: Is it intended that all associative arrays in fact refer to the same array? If you create a 'new' array by \newAssociativeArray{anotherword}  Associative arrays do not have any storage allocated until it is used, and the index expression is not restricted to integral expressions, but can be of any type. An associative array implements a look-up table of the elements of its declared type. The data type to be used as an index serves as the lookup key and imposes an ordering. Syntax // Value Array_Name [ key ]; data_type array_identifier [index_type ]; Initialization Example

if the array comes from the db, add a sort_order field so you can always be sure in what order the elements are in the array.

Array_Swap function in PHP, If for instance one of the two keys is not defined this will generate to pass the array as a reference to swap the values in the original array, Your method custom sorts the array while maintaining all associative relationships. In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

This may or may not be an option depending on your particular use-case, but if you initialize your array with null values with the appropriate keys before populating it with data, you can set the values in any order and the original key-order will be maintained. So instead of swapping elements, you can prevent the need to swap them entirely:

$arr = array('apple' => null,
             'pear' => null,
             'grapefruit' => null,
             'banana' => null);

...

$arr['apple'] = 'sweet';
$arr['grapefruit'] = 'bitter'; // set grapefruit before setting pear
$arr['pear'] = 'tasty';
$arr['banana'] = 'yellow';
print_r($arr);

>>> Array
(
    [apple] => sweet
    [pear] => tasty
    [grapefruit] => bitter
    [banana] => yellow
)

PHP – Swap Array Elements By Array Keys, could swap the array elements by the array keys. try it out. Done =) Reference: Stack Overflow - Switch two items in associative array PHP. Associative arrays give you another way to store information. When the size of the collection is unknown or the data space is sparse, an associative array is a better option. In Associative arrays Elements Not Allocated until Used. Index Can Be of Any Packed Type, String or Class.

How to loop through an associative array and get the key in PHP , Method 2: Using array_keys() function: The array_keys() is an inbuilt function in PHP which is used to return either all the keys of array or the subset of the keys. After an associative array is created, you can still modify the items in the array as follows: Edit a source item of the array. All instances of the source item will be updated automatically. Remove one or more items in the array. Replace one or more items in the array with selected objects. You can also add or delete objects associated with the array item.

Associative Arrays in PHP, We can loop through the associative array in two ways. First by using for loop and How to get a list of associative array keys in JavaScript ? How to access an  You can replace items in associative array. When you create an array, all items will be the same object. Sometimes we want to replace one or two items in array, but want to keep the associative array advantages. Associative array does allow you to do this. To replace items, click to select the associative array.

array_fill_keys - Manual, Change language: array_fill_keys — Fill an array with values, specifying keys If an associative array is used as the second parameter of array_fill_keys, then the Here's a slightly modified version than can handle 2 arrays as inputs: PHP Associative Arrays. Associative arrays are arrays that use named keys that you assign to them. There are two ways to create an associative array:

Comments
  • It's for using with Drupal form API, the order of the array determines the order each element (field) is printed. However, I can also use the '#weight' property to alter the order which it seems would be easier. It just means iterating over each field to set a new weight.
  • I agree with Lex. PHP does not provide a native function to swap array items. You can probably write your own with a combination of the rest of the array functions and lots of patience but, honestly, rewriting the full array with a foreach loop is by far the easiest method. A custom swap function is not worth the effort unless you handle very large arrays and, in such case, you should probably redesign that part of the code logic.
  • Is this supposed to be an answer? Well, I happen to have the same problem. I need to swap the order of any two elements in an array
  • Yes, this does answer the question, but Metti's answer is what people will be looking for (although note the comments).
  • +1, but it will blow up if one index exists and the other does not.
  • @Mathew: Indeed, but after fixing this problem it would serve the desired purpose well.
  • +1, this seems to be perfect for swapping elements of large arrays. For small, simple, two elements swap, I'd much more prefer a direct solution! :]
  • @trejder: but your direct solutions will not preserve keys!
  • +1 add this line to fix blowup: if (!isset($array[$key1]) || !isset($array[$key2])) {throw new InvalidArgumentException();}
  • If that was true, it'd make asort() any other builtin functions completely useless...
  • if you see i wrote "Classical associative array", not "php associative array". Function asort is specific to php implementation. again what i said is correct, one should assoc arrays for random access. if people would care look a bit wider than just PHP...
  • What's the problem of using PHP implementations when coding in PHP? Do you write language agnostic PHP code? What for? So you can run your PHP with a Perl interpreter? :-?