I wrote simple function array_swap
: swap two elements between positions swap_a
& swap_b
.
function array_swap(&$array,$swap_a,$swap_b){
list($array[$swap_a],$array[$swap_b]) = array($array[$swap_b],$array[$swap_a]);
}
For OP question (for example):
$items = array(
0 => 'contact',
1 => 'home',
2 => 'projects'
);
array_swap($items,0,1);
var_dump($items);
// OUTPUT
array(3) {
[0]=> string(4) "home"
[1]=> string(7) "contact"
[2]=> string(8) "projects"
}
Update
Since PHP 7.1 it's possible to do it like:
$items = [
0 => 'contact',
1 => 'home',
2 => 'projects'
];
[$items[0], $items[1]] = [$items[1], $items[0]];
var_dump($items);
// OUTPUT
array(3) {
[0]=> string(4) "home"
[1]=> string(7) "contact"
[2]=> string(8) "projects"
}
It's possible through Symmetric array destructuring.