Change $key Of Associative Array In A Foreach Loop In Php


Answer :

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;     } 

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

The answers here are dangerous, in the event that the key isn't changed, the element is actually deleted from the array. Also, you could unknowingly overwrite an element that was already there.

You'll want to do some checks first:

foreach($array as $key => $value) {     $newKey = ucfirst($key);      // does this key already exist in the array?     if(isset($array[$newKey])){         // yes, skip this to avoid overwritting an array element!         continue;     }      // Is the new key different from the old key?     if($key === $newKey){         // no, skip this since the key was already what we wanted.         continue;     }      $array[$newKey] = $value;     unset($array[$key]); } 

Of course, you'll probably want to combine these "if" statements with an "or" if you don't need to handle these situations differently.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?