fork(14) download
  1. <?php
  2.  
  3. $array = array('a' => 1, 'd' => 2, 'c' => 3); //associative array
  4.  
  5. // rename $array['d'] as $array['b']
  6. $array = replace_key_function($array, 'd', 'b');
  7.  
  8. var_export($array); // array('a' => 1, 'b' => 2, 'c' => 3); same order!
  9.  
  10. function replace_key_function($array, $key1, $key2)
  11. {
  12. $keys = array_keys($array);
  13. $index = array_search($key1, $keys);
  14.  
  15. if ($index !== false) {
  16. $keys[$index] = $key2;
  17. $array = array_combine($keys, $array);
  18. }
  19.  
  20. return $array;
  21. }
Success #stdin #stdout 0.02s 13112KB
stdin
Standard input is empty
stdout
array (
  'a' => 1,
  'b' => 2,
  'c' => 3,
)