How to add prefix to each key of PHP array?

藏色散人
Release: 2023-04-05 12:38:02
Original
4405 people have browsed it

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);
Copy after login

Output:

Array
(
[a0] => Hi
[a1] => Hello
[a2] => Hey
)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!