I have an array:
array( 0 => 'contact', 1 => 'home', 2 => 'projects' );
and I need to swap the 'contact' with 'home', so the array would be like:
array( 0 => 'home', 1 => 'contact', 2 => 'projects' );
how can I do this with PHP? :)
The array_flip() function is used to exchange the keys with their associated values in an array. The function returns an array in flip order, i.e. keys from array become values and values from array become keys. Note: The values of the array need to be valid keys, i.e. they need to be either integer or string.
The array_flip() function flips/exchanges all keys with their associated values in an array.
The built-in swap() function can swap two values in an array . template <class T> void swap (T& a, T& b); The swap() function takes two arguments of any data type, i.e., the two values that need to be swapped.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With