Home >Backend Development >PHP Tutorial >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:
<code class="php">foreach ($array as $k => $v) { $array[$prefix . $k] = $v; unset($array[$k]); }</code>
<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!