-1

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);      
   
}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • Just a quick heads up, the names - "Peter", "Kat", "Laura", these are the *keys*. The cities, "LEEDS", "bradford", "wakeFIeld", these are the *values*. There isn't such a thing as "key values" :) – bug56 Oct 20 '18 at 19:03
  • This question is Unclear because you have not clearly explained the logic, nor included the exact desired output. I don't know if you want [`$city[$name] = mb_convert_case($town, MB_CASE_TITLE, 'UTF-8');`](https://stackoverflow.com/a/68768405/2943403). – mickmackusa Oct 31 '22 at 22:23

2 Answers2

3

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);
Ernani Azevedo
  • 461
  • 2
  • 6
  • this doesn't work it is still returning the key values the same way as i declared in the original city array – ProgramMe26 Oct 20 '18 at 18:58
  • You declared cities as values, and people name as key. This code will change the city name (the value of the array key). – Ernani Azevedo Oct 20 '18 at 19:01
  • 1
    Make sure you're setting `$city[$key] = ucfirst ( strtolower ( $value));` like in this example. In your original code, your loop creates a proper town name, assigns it to `$town`, but never actually overwrites the old value, that's why it's still the same. In this example Ernani is setting `$city[$key]` explicitly to the new value – bug56 Oct 20 '18 at 19:01
  • ah okay i understand sorry i got confused. yes this code is working now and i have marked it as correct. apologies i am still new to php and still getting to grips with it. – ProgramMe26 Oct 20 '18 at 19:05
1

You are almost there, but your calls to ucfirst() and strtolower() are the wrong way round...

$town = strtolower($town);
$town = ucfirst($town);

This converts it all to lower case and then upper cases the first letter.

Or to abbreviate it a bit

$town = ucfirst(strtolower($town));

You also need to alter your foreach() to allow it to update the town...

foreach($city as $name => &$town) {

Add the & to allow it to update the town. Also move your last

print_r($city);

out of the loop.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55