user2403721
user2403721

Reputation: 23

Swap/exchange array keys php

Lets say I have an array:

Array
(
    [0] => 18208021789
    [1] => Ziggo-Humax iHDR5050C
    [2] => 191.90
    [4] => Something
    [5] => foo bar
}

And I want to change replace the place of [1] with [5], so as result I should have:

Array
(
    [0] => 18208021789
    [1] => foo bar
    [2] => 191.90
    [4] => Something
    [5] => Ziggo-Humax iHDR5050C
}

How can I achieve this with PHP?

Upvotes: 0

Views: 101

Answers (4)

sectus
sectus

Reputation: 15464

list($arr[1], $arr[5]) = array($arr[5], $arr[1]);

Read more about list. Also, list is not a function.

Upvotes: 2

Jeff Lee
Jeff Lee

Reputation: 781

You can use this function. Just copy it :D

 function swapPos(&$arr, $pos1, $pos2){
      $keys = array_keys($arr);
      $vals = array_values($arr);
      $key1 = array_search($pos1, $keys);
      $key2 = array_search($pos2, $keys);

      $tmp = $keys[$key1];
      $keys[$key1] = $keys[$key2];
      $keys[$key2] = $tmp;

      $tmp = $vals[$key1];
      $vals[$key1] = $vals[$key2];
      $vals[$key2] = $tmp;

      $arr = array_combine($keys, $vals);
    }

Upvotes: 1

$tmp = $array[1];
$array[1] = $array[5];
$array[5] = $tmp;

Upvotes: 1

anomaaly
anomaaly

Reputation: 841

$tmp=$arr[1];
$arr[1]=$arr[5];
$arr[5]=$tmp;

Upvotes: 2

Related Questions