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

How to Efficiently Prefix Array Keys in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 15:33:30151browse

How to Efficiently Prefix Array Keys in PHP?

Prefixing Array Keys Efficiently

To prepend a string to the beginning of all keys in an array, there are multiple approaches available.

One-Line Solution

The most concise solution involves a combination of array_map and array_combine:

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

Functional Approach

For versions of PHP 7.4 and above, an arrow function syntax can be employed:

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

Iterative Approach

A traditional loop-based solution is also available:

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

Pre-PHP 5.3 Custom Class

For older PHP versions, a custom class with a mapArray method can be used:

<code class="php">class KeyPrefixer {
    public function prefix(array $array, $prefix) {
        return $this->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;
    }
}

$prefix = "prefix";
$array = KeyPrefixer::prefix($array, $prefix);</code>

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