daGrevis
daGrevis

Reputation: 21333

How to swap keys with values in array?

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?

Upvotes: 15

Views: 26861

Answers (6)

Haim Evgi
Haim Evgi

Reputation: 125496

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.

Upvotes: 32

Fabio
Fabio

Reputation: 19176

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.

Upvotes: 5

Lukas Knuth
Lukas Knuth

Reputation: 25755

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

Upvotes: 2

PtPazuzu
PtPazuzu

Reputation: 2537

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

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

Upvotes: 2

Yoshi
Yoshi

Reputation: 54649

See: array_flip

Upvotes: 3

Shef
Shef

Reputation: 45589

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'
);

Upvotes: 4

Related Questions