Home  >  Article  >  Backend Development  >  How to Efficiently Prepend a Prefix to Array Keys in PHP?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-27 06:40:03175browse

 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>

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>
  • 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>

Historical Perspective

Prior to PHP 5.3, a different approach was necessary:

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

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!

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