PHP 4.3: Remove a specific key from an array

PHP 5+ provides the built-in function array_diff_key() which can be used to delete a certain key from an array.  Although I’m not proud of it, some of our customers’ sites are still running versions prior to PHP 5.  This is how we delete a specific key from an array in PHP 4+ (4.3).

 Let’s say that I have an array which contains the following:

$my_array = array(“key1″=> “apple”, “key2” => “orange”, “key3” => “banana”);

If I wanted to remove the key “key1”, and it’s associated value from the array, there is an array function array_diff_assoc() in PHP 4.3+ which compares 2 arrays, and deletes any key/value combinations from the first array which are present in the second, and returns the resulting array.  The problem is, that the key & value must be the same in both arrays.  This is the statement we used to delete the desired key:

$my_new_array = array_diff_assoc($my_array,array(“key1″=> $my_array[“key1”]));

Because we are reading the value of the key, from the desired array, we can be assured that the key/value combinations will match in both arrays, and the result will be a returned array, matching the original $my_array, but with “key1” => “apple” removed!

 You could also create a function to accomplish this:

function array_remove_key($target_array, $key){

          return array_diff_assoc($target_array,array($key => $target_array[$key]));