How to Efficiently Prepend a Prefix to Array Keys in PHP?

Mary-Kate Olsen
Release: 2024-10-27 06:40:03
Original
174 people have browsed it

 How to Efficiently Prepend a Prefix to Array Keys in PHP?

Prepending a Prefix to Array Keys Efficiently

When manipulating arrays, it's often necessary to add a prefix to all keys. This operation can be performed in several ways, but not all approaches are equally efficient.

Fastest Solution

The fastest solution is to use array_combine() in conjunction with array_map():

<code class="php">$prefix = "prefix";
$array = array_combine(
    array_map(fn($k) => $prefix . $k, array_keys($array)),
    $array
);</code>
Copy after login

This method iterates over the original array keys, appends the prefix, and creates a new array using array_combine() to reassign the keys and values accordingly.

Other Solutions

Other solutions include:

  • Using a foreach loop to iterate over each key and manually append the prefix, followed by unsetting the original key:
<code class="php">foreach ($array as $k => $v)
{
    $array[$prefix . $k] = $v;
    unset($array[$k]);
}</code>
Copy after login
  • Utilizing a custom KeyPrefixer class with an __construct() method and mapArray() method for efficiently performing the prefix operation:
<code class="php">$prefix = "prefix";
$array = KeyPrefixer::prefix($array, $prefix);</code>
Copy after login

Historical Perspective

Prior to PHP 5.3, a different approach was necessary:

<code class="php">$prefixer = new KeyPrefixer($prefix);
return $prefixer->mapArray($array);</code>
Copy after login

This method utilized a custom class and array_map() with an anonymous function to manipulate the keys and values.

The above is the detailed content of How to Efficiently Prepend a Prefix to Array Keys in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
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!