PHP Change Array Keys

php

Question

Array( 0 => 'blabla',
       1 => 'blabla',
       2 => 'blblll' ) etc..

Is there a way to change all the numeric keys to "Name" without looping through the array (so a php function)?

1
40
9/17/2014 5:06:02 PM

If you have an array of keys that you want to use then use array_combine

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

$list = array_combine($keys, array_values($list));

List will now be array('a' => 'blabla 1', ...) etc.

You have to use array_values to extract just the values from the array and not the old, numeric, keys.

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;
}

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

99
11/21/2008 1:52:37 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon