Home>Article>Backend Development> How to add prefix to each key of PHP array?
When you need to add a character or multiple characters to each key of an array, most people prefer to use a for loop or foreach loop to add keys. But we can do it without any loops. Then we mainly add a prefix to each key of the array by using the array_combine(), array_keys() and array_map() functions.
In the example below you can see how to use these functions together and add the prefix to each key in a faster way:
The code example is as follows:
'Hi','1'=>'Hello','2'=>'Hey']; $myNewArray = array_combine( array_map(function($key){ return 'a'.$key; }, array_keys($myArray)), $myArray ); print_r($myNewArray);
Output:
Array ( [a0] => Hi [a1] => Hello [a2] => Hey )
Related function introduction:
array_combine() function creates an array, using the value of an array as its key name, the value of another array as its value.
array_keys() function returns some or all of the key names in the array.
The array_map() function applies a callback function to each element of the array.
This article is about adding a prefix to each key in a PHP array. I hope it will be helpful to friends in need!
The above is the detailed content of How to add prefix to each key of PHP array?. For more information, please follow other related articles on the PHP Chinese website!