How to add prefix in array using PHP
PHP

How to add prefix in array using PHP

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.

Get The latest Coding solutions.

Subscribe to the Email Newsletter