1

I have an array that looks something like this:

array(
    0 => 'John',
    1 => 'Smith',
    3 => '123-456-7890'
    4 => '[email protected]'
)

And I would like to programmatically change the keys so that the array becomes an associative array:

array(
    'first' => 'John',
    'last'  => 'Smith',
    'phone' => '123-456-7890'
    'email' => '[email protected]'
)

What is the cleanest/most concise way of doing this?

2
  • yes, this particular array is just one iteration through a loop. It gets replaced each iteration. Commented Sep 20, 2011 at 15:08
  • actually, I'm writing a script to import an excel document where the columns could be in any order, but nice guess! Commented Sep 20, 2011 at 15:14

3 Answers 3

5

The array_combine() function is probably what you were looking for:

$keys = array('first', 'last', 'phone', 'email');

$new_arr = array_combine($keys, $arr);
Sign up to request clarification or add additional context in comments.

1 Comment

ooh...the problem with this approach (that I just discovered) is that it requires both arrays to have the same number of elements. I don't know how long the values array will be. I only need to assign keys to the first few items of the data array that I know will be there.
4

array_combine is probably the optimal approach here. If you have an ordered list you can merge it with the original keys again using:

$array = array_combine(array("first", "last", "phone", "email"), $list);

Comments

0

Assuming the array keys are constant, such that 0 is always firstname, 1 is last name, etc...

$new_keys = array(0 => 'first', 1 => 'last', 3 => 'phone', 4 => 'email');

foreach($new_keys as $oldkey => $newkey) {
   $orig_array[$newkey] = $orig_array[$oldkey];
   unset($orig_aray[$oldkey]);
}

If the mapping isn't constant, thne you'd have to build the $new_keys array dynamically each time, or just do the remapping by hand.

2 Comments

I was going to answer like this, but array_combine might be better.
It'd work, though if the source array has other keys not listed in the new keys list, it could be problematic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.