Search code examples
phparraysforeachlowercase

Lowercase all the associative array keys without foreach


I have this array which is held by this variable:

$get_multiple_role_will_redirect = isset($_POST['multiple_role_will_redirect']) ? $_POST['multiple_role_will_redirect'] : 0;

Array
(
    [Administrator] => 
    [Editor] => 
    [Author] => 
    [Contributor] => 
    [Subscriber] => 
    [Shop_manager] => 
    [Shop_accountant] => 
    [Shop_worker] => 
    [Shop_vendor] => 
    [Edd_subscriber] => 
    [Customer] => 
)

Now, I want to lowercase all the keys. To do that I am doing foreach like that:

$multiple_role_will_redirect = [];
foreach($get_multiple_role_will_redirect as $key => $value) {
    $key = strtolower($key);
    $multiple_role_will_redirect[$key] = $value;
}

My question is, Is there any other way without foreach loop to lowercase the array key?

I have checked with :

array_filter($get_multiple_role_will_redirect, 'strtolower');

But it's not lowercase the array key.


Solution

  • I think the array_change_key_case function works for you .

    $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
    print_r(array_change_key_case($age,CASE_LOWER));
    

    https://www.w3schools.com/php/func_array_change_key_case.asp