Home  >  Article  >  Backend Development  >  How to add prefix to each key of PHP array?

How to add prefix to each key of PHP array?

藏色散人
藏色散人Original
2019-02-28 10:46:284379browse

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.

How to add prefix to each key of PHP array?

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:

<?php
$myArray = [&#39;0&#39;=>&#39;Hi&#39;,&#39;1&#39;=>&#39;Hello&#39;,&#39;2&#39;=>&#39;Hey&#39;];
$myNewArray = array_combine(
array_map(function($key){ return &#39;a&#39;.$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn