mike
mike

Reputation:

Swap the position of two elements in an array by known keys

What would be a good way of swapping the value at key 1 with the value of key 2?

original

Array
(
    [0] => Text1
    [1] => World
    [2] => Hello
)

after

Array
(
    [0] => Text1
    [1] => Hello
    [2] => World
)

Upvotes: -1

Views: 150

Answers (3)

mickmackusa
mickmackusa

Reputation: 47761

In modern PHP which offers "symmetric array destructuring" (PHP7.1 and up), you can avoid declaring a temporary value and simply assign the new values to the desired keys in the left side of the destructuring expression. This technique can be extended to accommodate swapping more than two elements at once. Demo

$array = ["Text1", "Hello", "World"];

[2 => $array[1], 1 => $array[2]] = $array;

var_export($array);

Output:

array (
  0 => 'Text1',
  1 => 'World',
  2 => 'Hello',
)

Upvotes: 0

Legion
Legion

Reputation: 1497

$A = array("Text1", "Hello", "World");
$tmp = $A[2];
$A[2] = $A[1];
$A[1] = $tmp;

Upvotes: 0

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58351

If it's a simple as that,

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

Upvotes: 4

Related Questions