14

I have array like:

array(
  0 => 'a',
  1 => 'b',
  2 => 'c'
);

I need to convert it to:

array(
  'a',
  'b',
  'c'
);

What's the fastest way to swap keys with values?

daGrevis
  • 21,014
  • 37
  • 100
  • 139
  • 2
    array_flip maybe? It does exactly what you **said**, not what you want (because what you want is not really meaningful). – Michael J.V. Jul 27 '11 at 13:25
  • 2
    Use [array_flip](http://blog.jterminal.com/2014/07/use-php-array_flip-function-to-exchange-keys-and-associated-values-in-an-array.html) to swap keys with values. – Jasir Jul 12 '14 at 19:44

6 Answers6

31

PHP has the array_flip function which exchanges all keys with their corresponding values, but you do not need it in your case because the arrays are the same.

array(
  'a',
  'b',
  'c'
);

This array has the keys 0, 1, and 2.

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
4

Use array_flip(). That will do to swap keys with values. However, your array is OK the way it is. That is, you don't need to swap them, because then your array will become:

array(
  'a' => 0,
  'b' => 1,
  'c' => 2
);

not

array(
  'a',
  'b',
  'c'
);
Shef
  • 44,808
  • 15
  • 79
  • 90
4
array(
  0 => 'a',
  1 => 'b',
  2 => 'c'
);

and

array(
  'a',
  'b',
  'c'
);

are the same array, the second form has 0,1,2 as implicit keys. If your array does not have numeric keys you can use array_values function to get an array which has only the values (with numeric implicit keys).

Otherwise if you need to swap keys with values array_flip is the solution, but from your example is not clear what you're trying to do.

Fabio
  • 18,856
  • 9
  • 82
  • 114
3

See: array_flip

Yoshi
  • 54,081
  • 14
  • 89
  • 103
2

$flipped_arr = array_flip($arr); will do that for you.

(source: http://php.net/manual/en/function.array-flip.php)

PtPazuzu
  • 2,497
  • 1
  • 17
  • 10
2

You'll want to use array_flip() for that.

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111