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

前端 未结 6 1970
故里飘歌
故里飘歌 2020-12-18 22:11

I have an array like this:

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

I need to loop over every elemen

相关标签:
6条回答
  • 2020-12-18 22:28

    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;
        }
    
    0 讨论(0)
  • 2020-12-18 22:29

    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.

    0 讨论(0)
  • 2020-12-18 22:30

    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.

    0 讨论(0)
  • 2020-12-18 22:34

    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
    0 讨论(0)
  • 2020-12-18 22:41

    If you use laravel or have Illuminate\Support somewhere in your dependencies, here's a chainable way:

    >>> collect($array)
            ->keys()
            ->map(function ($key) {
                return ucfirst($key);
            })
            ->combine($array);
    
    => Illuminate\Support\Collection {#1389
         all: [
           "FirstName" => "Joe",
           "LastName" => "Smith",
         ],
       }
    
    0 讨论(0)
  • 2020-12-18 22:42

    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.

    0 讨论(0)
提交回复
热议问题