jkushner jkushner - 3 months ago 17
PHP Question

Change array keys to lowercase

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.

Answer

You can achieve the same thing with array_walk using references.

Like so:

array_walk(array_keys($a), function ($k) use (&$items) {
    $value = $items[$k];
    unset($items[$k]);
    $items[$this->normalizeKey($k)] = $value;
});

You can get apply the same to foreach

Comments