How to rename array keys in PHP?
When I var_dump on a variable called $tags (a multidimensional array) I get this:
Array ( [0] => Array ( [name] => tabbing [url] => tabbing ) [1] => Array ( [name] => tabby ridiman [url] => tabby-ridiman ) [2] => Array ( [name] => tables [url] => tables ) [3] => Array ( [name] => tabloids [url] => tabloids ) [4] => Array ( [name] => taco bell [url] => taco-bell ) [5] => Array ( [name] => tacos [url] => tacos ) )
I would like to rename all array keys called "url" to be called "value". What would be a good way to do this?
Solution 1:
You could use array_map()
to do it.
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
Solution 2:
Loop through, set new key, unset old key.
foreach($tags as &$val){
$val['value'] = $val['url'];
unset($val['url']);
}
Solution 3:
Talking about functional PHP, I have this more generic answer:
array_map(function($arr){
$ret = $arr;
$ret['value'] = $ret['url'];
unset($ret['url']);
return $ret;
}, $tag);
}