tags:

views:

51

answers:

3

Is it possible to edit the key once it has been made?

I know you can create an array with a different key but I couldn't see anything on the php site about editing the key latter.

Original array:

Array
(
    [0] => first
    [1] => color
)

What I would like:

Array
(
    [newName] => first
    [1] => color
)
A: 
$array = array('foo', 'bar');

$array['newName'] = $array[0];
unset($array[0]);

That's pretty much the only thing you can do.

deceze
That changes the order of the array.
Andrew Moore
+2  A: 

If you want to change the key of an item, you must either set the value with the new key and unset() the old one (this technique changes the order of the array):

$arr['newName'] = $arr[0];
unset($arr[0]);

or use a wrapper that forgoes looping and allows you to modify the keys, as such:

function array_change_key(&$array, $search, $replace) {
    $keys = array_keys($array);
    $values = array_values($array);

    // Return FALSE if replace key already exists
    if(array_search($replace, $keys) !== FALSE) return FALSE;

    // Return FALSE if search key doesn't exists
    $searchKey = array_search($search, $keys); 
    if($searchKey === FALSE) return FALSE;

    $keys[$searchKey] = $replace;
    $array = array_combine($keys, $values);

    return TRUE; // Swap complete
}
Andrew Moore
+1  A: 

Here's an alternate, simple approach, which is probably fairly efficient, as long as you do all of your re-keying for each array in a single call:

<?php
function mapKeys(array $arr, array $map) {
  //we'll build our new, rekeyed array here:
  $newArray = array();
  //iterate through the source array
  foreach($arr as $oldKey => $value) {
    //if the old key has been mapped to a new key, use the new one.  
    //Otherwise keep the old key
    $newKey = isset($map[$key]) ? $map[$key] : $oldKey;
    //add the value to the new array with the "new" key
    $newArray[$newKey] = $value;
  }
  return $newArray;
}

$arr = array('first', 'color');
$map = array(0 => 'newName');

print_r(mapKeys($arr, $map));
Frank Farmer