1

I have two keys and want to swap them in a multidimensional array.

I Have referred these Swap array values with php, How to swap two values in array with indexes? references but didn't get any help.

I have this array,

[
    'box-a' => 'email',
    'box-b' => 'job',
    'box-c' => 'company',
    'box-d' => 'candidate',
    'box-e' => 'calender',
    'box-f' => 'smartlist',
    'box-g' => 'analytics',
]

And I want to swap two array keys, box-b and box-e but the array values should remain as it is.

I have tried this,

list($array[$swap_a], $array[$swap_b]) = array($array[$swap_b], $array[$swap_a]);

But didn't get success. Where am I wrong?

Keyur
  • 1,113
  • 1
  • 23
  • 42

2 Answers2

2

Try to use temp array, like this:

$a = [
'box-a' => 'email',
'box-b' => 'job',
'box-c' => 'company',
'box-d' => 'candidate',
'box-e' => 'calender',
'box-f' => 'smartlist',
'box-g' => 'analytics',
];

$temp = $a['box-e'];
$a['box-e'] = $a['box-b'];
$a['box-b'] = $temp;
Grynets
  • 2,477
  • 1
  • 17
  • 41
2

You can use array_replace() in a one-liner, and avoid using temporary data storage.

Code: (Demo)

$a = [
'box-a' => 'email',
'box-b' => 'job',
'box-c' => 'company',
'box-d' => 'candidate',
'box-e' => 'calender',
'box-f' => 'smartlist',
'box-g' => 'analytics'
];

var_export(array_replace($a,['box-b'=>$a['box-e'],'box-e'=>$a['box-b']]));

Output:

array (
  'box-a' => 'email',
  'box-b' => 'calender',
  'box-c' => 'company',
  'box-d' => 'candidate',
  'box-e' => 'job',
  'box-f' => 'smartlist',
  'box-g' => 'analytics',
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136