Is there a way to change all keys in a flat indexed array to the same string (“Name”)? [closed]

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.

Leave a Comment