Change $key of associative array in a foreach loop in php

You can't modify the keys in a foreach, so you would need to unset the old one and create a new one. Here is another way:

$array = array_combine(array_map('ucfirst', array_keys($array)), $array);
  1. Get the keys using array_keys
  2. Apply ucfirst to the keys using array_map
  3. Combine the new keys with the values using array_combine

unset it first in case it is already in the proper format, otherwise you will remove what you just defined:

foreach($array as $key => $value)
    {
        unset($array[$key]);
        $array[ucfirst($key)] = $value;
    }