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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 20:47:02674browse

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

Efficient Key Prefixing for Array

To prepend a string to all keys in a flat array, consider the following approaches:

One-Line Solution:

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

Iterative Approach:

<code class="php">$prefix = "prefix";
foreach ($array as $k => $v) {
    $array[$prefix . $k] = $v;
    unset($array[$k]);
}</code>

Historical Approach (Pre-PHP 5.3):

<code class="php">class KeyPrefixer {
    private $prefix;
    public function __construct($prefix) {
        $this->prefix = (string)$prefix;       
    }
    public static function prefix(array $array, $prefix) {
        $prefixer = new KeyPrefixer($prefix);
        return $prefixer->mapArray($array);
    }
    public function mapArray(array $array) {
        return array_combine(
            array_map(array($this, 'mapKey', array_keys($array)),
            $array
        );
    }
    public function mapKey($key) {
        return $this->prefix . (string)$key;
    }
}</code>

The above is the detailed content of How to Efficiently Prepend a String 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