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

前端 未结 6 1975
故里飘歌
故里飘歌 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: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

提交回复
热议问题