How to replace keys in an associative array

PHP has a pretty decent set of array functions for manipulating arrays, but I was a little surprised to see few functions that dealt with key manipulation.

It might not be quite as common a need to manipulate or replace the keys of an associative array, but it could be quite useful when maintaining a standardised format, for example when dealing with user data. Another possible use could be when displaying data directly from a database table.

It’s often convenient to use the database table column names when displaying table data, but those column names might not necessarily be in a user-friendly format. It’s fairly common to see underscores or CamelCase used in column names for readability. Great for programmers, but not so great for published content.

When working with query results as an associative array, this function could be one way to deal with that issue. For underscores, a simple find/replace. For CamelCase, a space before the second capitalised letter. Depending on your circumstances, this might be better accomplished with SQL aliases for simpler column name replacements.

Replacing a key is a little trickier than replacing a value, because you can’t change the key name directly. Instead, you copy the value from the old key, assign it to the new key, then delete the old key where the value was originally held.



This function is relatively straight forward. It checks to see if a key exists in a 2-dimensional array, and replaces the key with function parameter $newkey. The function returns true on success, and false on failure.

Example usage


This example demonstrates directly replacing one key with another, and using a foreach loop to iterate over all of the keys and make them upper case. This second example actually closely resembles the built-in PHP function array_change_key_case(), however by iterating over the keys with replaceKey(), any sort of string manipulation may be performed on the keys.

Leave a Reply

Your email address will not be published. Required fields are marked *