Change the key of an Array Element

57

This article explains how to change the key of an array element. An array is a special variable, which can hold more than one value at a time. Normally, if there is a list of array, it is usually a key value pair (key => value). While changing the key, we need to preserve the respective value also. So, I will show you couples of example to do that with example.

Note:
If you are familiar with Laravel, you can learn to create a CRUD application in laravel by following Laravel 5.6 CRUD Application from scratch article

Method 1

Suppose, $array is an array with some key value pair. We need to change the key name city to state.

 "vijayrana", "city" => "kathmandu", "county" => "nepal",  );

    $array["state"] = $array["city"];   //assign new key name to old key
    unset($array["city"]);  //unset the old key
    
    var_dump($array);exit();

Output:

 string 'vijayrana' (length=9)
      'county' => string 'nepal' (length=5)
      'state' => string 'kathmandu' (length=9)

Here, city key is assigned to state key. Since, assigning the key city to state doesn’t remove the old key value pair. So, we need to remove the old key using unset.
Note:
The above example works but it doesn’t preserve the order of array. When you run the code, the changed key value pair is moved to last one.

Method 2

The second method uses a helper class function where values are sent as parameter. Oh! Talk is cheap, let me show you the code.

 "vijayrana", "city" => "kathmandu", "county" => "nepal",  );
    
    function replace_key($array, $old_key, $new_key) {
        $keys = array_keys($array);
    
        if (false === $index = array_search($old_key, $keys)) {
            throw new Exception(sprintf('Key "%s" does not exit', $old_key));
        }
    
        $keys[$index] = $new_key;
    
        return array_combine($keys, array_values($array));
    }

    $array = replace_key($array, "name", "FullName");
    $array = replace_key($array, "city", "State");

    var_dump($array); exit();

Output:

 string 'vijayrana' (length=9)
      'State' => string 'kathmandu' (length=9)
      'county' => string 'nepal' (length=5)

A helper function is defined replace_key where array variable name, old key and new key to change are passed as parameter . array_keys is used to return all the keys or a subset of the keys of an array. array_search is used to search the array for a given value and returns the corresponding key if successful. And lastly, array_combine is used to create an array by using one array for keys and another for its values.

LEAVE A REPLY

Please enter your comment!
Please enter your name here