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.
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).
Associative arrays are arrays that use named keys that you assign to them.
The array_keys() function returns an array containing the keys.
Using array_walk
array_walk($array, function (& $item) {
$item['new_key'] = $item['old_key'];
unset($item['old_key']);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With