Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?

like image 479
Thomas Owens Avatar asked Oct 27 '08 17:10

Thomas Owens


People also ask

How do you change the key of an array?

Description ¶array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array.

How do I change the index of an array element in PHP?

We will use array_values() function to get all the values of the array and range() function to create an array of elements which we want to use as new keys or new index of the array (reindexing). Then the array_combine() function will combine both the array as keys and values.

Which function is used to change key case PHP array?

The array_change_key_case() function changes all keys in an array to lowercase or uppercase.


1 Answers

$arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]); 
like image 51
KernelM Avatar answered Oct 21 '22 17:10

KernelM