Reset keys of array elements using PHP ?
In PHP, two types of arrays are possible indexed and associative array. In case of Indexed array, the elements are strictly integer indexed and in case of associative array every element has corresponding keys associated with them and the elements can only be accessed using these keys.
To access the keys and values of an associative array using integer index the array_keys() and array_values() inbuilt functions can be used.
- The array_keys() function takes input an array and returns the indexed array of only keys from the input array.
- The array_values() function takes input an array and return the indexed array of only values from the input array.
Now, to reset the keys of array elements two operations can be performed, key_swap() and key_change(). As these are not inbuilt function these has to implemented in the code.
Using key_swap() function: This function will take input an array and two keys and then swap the values corresponding to these two keys with the help of another variable ($val) and returns the resulting array.
Note: This function will throw an error if both the keys are not present in the array.
Using key_change() function: This function will take input an array and two keys, one old key (already present in the array) and a new key. The function will first store the value corresponding to the old key in to a third variable ($val) and then delete (unset()) the old key and its corresponding value from the array. Then the new key will be added to the array the value stored in the third variable ($val) will be assigned to it and the resulting array will be returned.
Note: This function will return desired output if the new key is not present in the array otherwise if the new key in present in the input array then value of the new key will be lost as the value of the old key will overwrite it. Also, the function will throw an error if the old key is not present in the input array.
Program: PHP program to reset keys of array element in an array.
The Sample array: Array ( [zero] => 1 [one] => 2 [two] => 0 [test] => 3 ) The Modified array: Array ( [zero] => 0 [one] => 1 [two] => 2 [three] => 3 )