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

26,695

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

This might work:

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

but it is very risky to modify an array like this while you're looping on it. You might be better off to store the unsettable keys in another array, then have a separate loop to remove them from the original array.

And of course, this doesn't check for possible collisions in the aray, e.g. firstname -> FirstName, where FirstName already existed elsewhere in the array.

But in the end, it boils down to the fact that you can't "rename" a key. You can create a new one and delete the original, but you can't in-place modify the key, because the key IS the key to lookup an entry in the aray. changing the key's value necessarily changes what that key is pointing at.

Solution 5

Top of my head...

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

Slightly change your way of thinking. Instead of modifying an existing element, create a new one, and remove the old one.

Share:
26,695
brianwalleshauser
Author by

brianwalleshauser

Actively developing in Magento 1.9.x.x since April 2014

Updated on July 09, 2022

Comments

  • brianwalleshauser
    brianwalleshauser almost 2 years

    I have an array like this:

    array(
        'firstName' => 'Joe',
        'lastName'  => 'Smith'
        )
    

    I need to loop over every element in my array and in the end, the array should look like this:

    array(
        'FirstName' => 'Joe',
        'LastName'  => 'Smith'
        )
    

    Failed idea was:

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

    This obviously will not work, because the array is not passed by reference. However, all these attempts also fail:

        foreach(&$array as $key => $value)
        {
            $key = ucfirst($key);
        }
    
    
        foreach($array as &$key => $value)
        {
            $key = ucfirst($key);
        }
    

    Pretty much at my wits end with this one. I'm using Magento 1.9.0.1 CE, but that's pretty irrelevant for this problem. If you must know, the reason I have to do this is because I have a bunch of object that's I'm returning as an array to be assembled into a SOAP client. The API I'm using requires the keys to begin with a capital letter...however, I don't wish to capitalize the first letter of my object's variable names. Silly, I know, but we all answer to someone, and that someone wants it that way.

  • Tim
    Tim almost 6 years
    In the case that the key already has the first letter uppercased, won't this just remove that entry from the array altogether? Should be unset then assign, right?
  • lpaseen
    lpaseen over 5 years
    @Tim that is exactly what I was thinking also and sure enough that is what happens. Better add "if (ucfirst($key)==$key) continue;" as first line in the loop.