Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap keys with values in array?

Tags:

arrays

php

key

swap

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?

like image 873
daGrevis Avatar asked Jul 27 '11 13:07

daGrevis


People also ask

How do you replace a key in an array?

The array_replace() function replaces the values of the first array with the values from following arrays. Tip: You can assign one array to the function, or as many as you like. If a key from array1 exists in array2, values from array1 will be replaced by the values from array2.

What is the use of array_flip?

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

Is array key value pair?

Arrays in javascript are typically used only with numeric, auto incremented keys, but javascript objects can hold named key value pairs, functions and even other objects as well. Simple Array eg.


2 Answers

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'
);
like image 20
Shef Avatar answered Sep 20 '22 16:09

Shef


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.

like image 93
Haim Evgi Avatar answered Sep 18 '22 16:09

Haim Evgi