Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change key in associative array in PHP

Say I have an array like this:

array(2) {
  [0]=> array(2) {
    ["n"]=> string(4) "john"
    ["l"]=> string(3) "red"
  }
  [1]=> array(2) {
    ["n"]=> string(5) "nicel"
    ["l"]=> string(4) "blue"
  }
}

How would I change the keys of the inside arrays? Say, I want to change "n" for "name" and "l" for "last_name". Taking into account that it can happen than an array doesn't have a particular key.

like image 406
Hommer Smith Avatar asked Nov 05 '12 13:11

Hommer Smith


People also ask

How do you change the key in an associative array?

Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Show activity on this post. Renaming the key AND keeping the ordering consistent (the later was important for the use case that the following code was written).

What is key in associative array in PHP?

Associative arrays are arrays that use named keys that you assign to them.

What is Array_keys () used for in PHP?

The array_keys() function returns an array containing the keys.


1 Answers

Using array_walk

array_walk($array, function (& $item) {
   $item['new_key'] = $item['old_key'];
   unset($item['old_key']);
});
like image 137
anydasa Avatar answered Sep 20 '22 02:09

anydasa