Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change array keys to lowercase

Tags:

arrays

php

I'm looking for a nifty php solution to replace a standard forloop. i dont care at all about the inner workings of my normalize method.

Here is my code:

$pairs=[];
foreach($items as $key => $val){
    $key = $this->normalizeKey($key);
    $pairs[$key] = $val;
}

private function normalizeKey($key)
{
    // lowercase string
    $key = strtolower($key);

    // return normalized key
    return $key;
}   

I'd like to learn the PHP language a bit better. I thought array_walk would be nice to use, but that operates on the values and not the keys.

I am looking for a PHP array method that can perform this code instead of a foreach loop.

like image 568
somejkuser Avatar asked Oct 31 '25 01:10

somejkuser


2 Answers

You want array_change_key_case

$pairs = array_change_key_case($items);
like image 171
Sherif Avatar answered Nov 02 '25 20:11

Sherif


Just for fun, though it requires three functions. You can replace strtolower() with whatever since this can already be done with array_change_key_case():

$pairs = array_combine(array_map('strtolower', array_keys($items)), $items);
  • Get the keys from $items
  • Map the array of keys to strtolower()
  • Combine the new keys with $items values

You can also use an anonymous function as the callback if you need something more complex. This will append -something to each key:

$pairs = array_combine(array_map(function ($v) {
                                     return $v . '-something';
                                 },
                       array_keys($items)), $items);
like image 39
AbraCadaver Avatar answered Nov 02 '25 19:11

AbraCadaver