0

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

2 Answers 2

4

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) );
Sign up to request clarification or add additional context in comments.

Comments

0

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 )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.