pixie123
pixie123

Reputation: 979

Replace character in associate array keys

i want to replace underscore with hyphen (dash) in all the keys in my $array and nothing else.

Here is my array:

Array ( [username] => bob [email] => [email protected] [first_name] => Bob [last_name] => Jones [picture] => /images/no-picture.png [birthday] => )

in this example, i want to replace [first-name] with [first_name] and ever other key that has a - to be replaced with _. i ONLY want the key an not the value. for example, i do NOT want no-picture.png because that is a value. thanks!

$test = str_replace('-', '_', $array);

Upvotes: 0

Views: 1434

Answers (2)

Calos
Calos

Reputation: 1942

Use array_keys() get keys after use array_combine() bind new keys:

<?php
function replaceArrayKeys( $array ) {
    $replacedKeys = str_replace('-', '_', array_keys($array));
    return array_combine($replacedKeys, $array);
}

$array =[
    'username' => 'bob',
    'email' => '[email protected]',
    'first-name' => 'Bob',
    'last-name' => 'Jones',
    'picture' => '/images/no-picture.png',
    'birthday' => '1',
];

print_r( replaceArrayKeys($array) );

Upvotes: 4

rescobar
rescobar

Reputation: 1305

Another solution is using array_map:

function setHyphen(&$array){
   $array= array_combine(array_map(function($str){ return str_replace("_","-",$str); }, array_keys($array)),array_values($array));
}
setHyphen($array);
print_r($array);

Ouput:

Array ( 
    [username] => bob 
    [email] => [email protected] 
    [first-name] => Bob 
    [last-name] => Jones 
    [picture] => /images/no-picture.png 
    [birthday] => 123 )

Upvotes: 0

Related Questions