Cara menggunakan php change array key

DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.

You can change array key too easily but doing it without changing the order in PHP is quite tricky. Simply assigning the value to a new key and deleting old one doesn’t change the position of the new key at the place of old in the array.

So in this article, I have explained 3 ways to let you change array key while maintaining the key order and last one of them can be used with a multidimensional array as well. But before that, if you just need to rename a key without preserving the order, the two lines code does the job:

Cara menggunakan php change array key

$arr[$newkey]=$arr[$oldkey];

unset($arr[$oldkey]);

  • PHP Interview Questions.
  • Convert a multidimensional array to object.

1. Change Array Key using JSON encode/decode

functionjson_change_key($arr,$oldkey,$newkey){

$json= str_replace('"'.$oldkey.'":','"'.$newkey.'":',json_encode($arr));

return json_decode($json);

}

It’s short but be careful while using it. Use only to change key when you’re sure that your array doesn’t contain value exactly same as old key plus a colon. Otherwise, the value or object value will also get replaced.

2. Replace key & Maintain Order using Array Functions in PHP

functionreplace_key($arr,$oldkey,$newkey){

if(array_key_exists($oldkey, $arr)){

$keys=array_keys($arr);

     $keys[array_search($oldkey, $keys)]=$newkey;

    returnarray_combine($keys,$arr);

}

    return $arr;    

}

The functionreplace_key() first checks if old key exists in the array? If yes then creates an Indexed Array of keys from source array and change old key with new using PHP array_search() function.

Finally, array_combine() function returns a new array with key changed, taking keys from the created indexed array and values from source array. The non-existence of old key just simply returns the array without any change.

3. Change Array Key without Changing the Order (Multidimensional Array Capable)

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

//$arr => original array

//$set => array containing old keys as keys and new keys as values

functionrecursive_change_key($arr,$set){

        if (is_array($arr)&& is_array($set)) {

     $newArr = array();

     foreach($arr as$k=>$v) {

         $key=array_key_exists($k,$set)?$set[$k]: $k;

         $newArr[$key]=is_array($v)?recursive_change_key($v, $set):$v;

     }

     return$newArr;

     }

     return$arr;    

    }

    $ppl=array(

        'jack'=>array('address_2'=>'London','country' =>'UK'),

        'jill'=>array('address_2'=>'Washington','country'=>'US')

    );

   $people=recursive_change_key($ppl,array('jill'=>'john','address_2'=>'city'));

   print_r($people);

/*

====================================

Output:

Array

(

    [jack] => Array

        (

            [city] => London

            [country] => UK

        )

    [john] => Array

        (

            [city] => Washington

            [country] => US

        )

)

*/

This solution is quite elegant and can work with multidimensional array too with help of classic PHP loop and recursive function call. Let’s see how are we doing this change.

Here we need to pass two arrays in the function call (Line #20). The first parameter is the array which needs to change keys and another is an array containing indexes as old keys and values as new keys. Upon execution, the function will change all the keys in the first array which are present in the second array too and their respective values will be new keys.

The recursive calling within function ensures changing keys up to the deepest branch of the array. The functionrecursive_change_key() here is provided along with the example to understand better.

Don’t forget to read our extensive list of 38 PHP related tutorials yet.

So here you got 3 ways to change array key without changing the order of array in PHP. And the last one works with a multidimensional array as well. All you need is just to provide correct set of “old key, new key” pairs for changing purpose.