How to add prefix in each key of PHP Array?

By Hardik Savani | February 13, 2016 | | 47535 Viewer | Category : PHP


Whenever you require to add one character or more to each and every key of array then most of the people would like prefer add key using for loop or foreach loop. But we can do this without using any kind of loop. using array_combine(), array_keys() and array_map() through we can add prefix on each key of array, In Bellow example you can see how to use both function together and add faster way to add prefix of every item key:

Example:

$myArray = ['0'=>'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

)



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.