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

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

Susan Sarandon
Susan SarandonOriginal
2024-10-26 14:18:30530browse

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

Adding a Prefix to Array Keys Efficiently

The imperative question is: How to efficiently add a prefix to the keys of a flat array?

Solution 1: Using PHP >= 7.4 Arrow Functions

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

Solution 2: Using an External Class (PHP < 5.3)

For PHP versions prior to 5.3, the following class-based approach can be used:

<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;
    }
}

$prefix = "prefix";
$array = KeyPrefixer::prefix($array, $prefix);<h3>Additional Approaches</h3>
<ul><li><strong>Using a Loop (PHP >= 5.3)</strong></li></ul>
<pre class="brush:php;toolbar:false"><code class="php">$prefix = "prefix";
foreach ($array as $k => $v)
{
    $array[$prefix . $k] = $v;
    unset($array[$k]);
}</code>
  • Using array_combine() with create_function() (PHP < 5.3)

Not recommended due to security concerns.

<code class="php">$array = array_combine(
    array_map(create_function('$k', 'return "prefix$k";'), array_keys($array)),
    $array
);</code>

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