Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap array values with php

Tags:

arrays

php

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? :)

like image 661
Sergio Toledo Piza Avatar asked Jul 02 '12 17:07

Sergio Toledo Piza


People also ask

How to interchange key value in array 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.

How do I flip an array in PHP?

The array_flip() function flips/exchanges all keys with their associated values in an array.

How do you swap 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.


1 Answers

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.

like image 88
voodoo417 Avatar answered Oct 09 '22 01:10

voodoo417