Search code examples
phparraysstringuppercaselowercase

Have key value in associative array be uppercase first letter and the rest of the string lowercase


I have declared an associative array in php and assigned it key values that have a mixture of lower and uppercase letters. I need the key values in the array to be uppercase first and string the rest of the way and it needs to be in a foreach loop.

$city=array('Peter'=>'LEEDS',
            'Kat'=>'bradford',
            'Laura'=>'wakeFIeld');
print_r($city);
echo '<br />';

foreach($city as $name => $town) {
   
   $town = ucfirst($town);
   $town = strtolower($town);
   print_r($city);      
   
}

Solution

  • You need to lowercase the key first, than use ucfirst. Your code will be like this:

    $city = array ( "Peter" => "LEEDS", "Kat" => "bradford", "Laura" => "wakeFIeld");
    print_r ( $city);
    echo "<br />";
    
    foreach ( $city as $key => $value)
    {
      $city[$key] = ucfirst ( strtolower ( $value));
    }
    print_r ( $city);