How to add prefix in array using PHP

Avatar
C

Callum Davies

Senior Backend Engineer••
8270Views
5mRead
0Reactions

In PHP, you can add a prefix to all keys in an array by iterating through the array and modifying the keys. Here's an example of how you can achieve this:

<?php

function addPrefixToKeys(array $inputArray, string $prefix): array {
    $outputArray = array();
    
    foreach ($inputArray as $key => $value) {
        $newKey = $prefix . $key;
        $outputArray[$newKey] = $value;
    }
    
    return $outputArray;
}

// Example usage:
$inputArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

$prefix = 'prefix_';

$resultArray = addPrefixToKeys($inputArray, $prefix);

// Output the modified array
print_r($resultArray);
?>

In this example, the function addPrefixToKeys takes an input array and a prefix as arguments, and it returns a new array with keys having the specified prefix.

Please note that this function creates a new array with the modified keys and leaves the original array unchanged. If you want to modify the original array in place, you can use the reference operator & when iterating through the array:

function addPrefixToKeysInPlace(array &$inputArray, string $prefix): void {
    foreach ($inputArray as $key => &$value) {
        $newKey = $prefix . $key;
        unset($inputArray[$key]); // Remove the old key
        $inputArray[$newKey] = $value;
    }
}

// Example usage:
$inputArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);

$prefix = 'prefix_';

addPrefixToKeysInPlace($inputArray, $prefix);

// Output the modified array
print_r($inputArray);

Be cautious when modifying arrays in place, as it can have unintended consequences, especially if the array is used elsewhere in your code.Hope it will help you. Thank you for reading this article.

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?What's your production setup for this scenario? Have you encountered similar architectural bottlenecks or edge-case gotchas?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles