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

How to Efficiently Prefix Array Keys in PHP?

Mary-Kate Olsen
Release: 2024-10-26 15:33:30
Original
229 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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