Reputation:
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
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
Reputation: 1497
$A = array("Text1", "Hello", "World");
$tmp = $A[2];
$A[2] = $A[1];
$A[1] = $tmp;
Upvotes: 0
Reputation: 58351
If it's a simple as that,
$tmp = $array[1];
$array[1] = $array[2];
$array[2] = $tmp;
Upvotes: 4