How to add prefix in each key of PHP Array?

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

Share this post:

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:


$myArray = ['0'=>'Hi','1'=>'Hello','2'=>'Hey'];

$myNewArray = array_combine(

array_map(function($key){ return 'a'.$key; }, array_keys($myArray)),







[a0] => Hi

[a1] => Hello

[a2] => Hey