In PHP, how do you change the key of an array element?

后端 未结 23 2345
逝去的感伤
逝去的感伤 2020-11-22 03:45

I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an I

23条回答
  •  不思量自难忘°
    2020-11-22 04:37

    One which preservers ordering that's simple to understand:

    function rename_array_key(array $array, $old_key, $new_key) {
      if (!array_key_exists($old_key, $array)) {
          return $array;
      }
      $new_array = [];
      foreach ($array as $key => $value) {
        $new_key = $old_key === $key
          ? $new_key
          : $key;
        $new_array[$new_key] = $value;
      }
      return $new_array;
    }
    

提交回复
热议问题