December 17, 2007

PHP 4.3: Remove a specific key from an array

Filed under: PHP — Soleer @ 10:43 pm

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]));

}

3 Comments »

  1. Thanks. This is just the concise solution I was looking for. I’ll give it a try.

    Comment by Adam C. — December 18, 2007 @ 9:06 am

  2. Found several posts on the web. Only this one wins my vote. Thanks!

    Comment by JC — February 23, 2008 @ 10:09 am

  3. thanks man!

    Comment by john — August 20, 2008 @ 7:15 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Who we are

Explore our history and character.

If you've ever been on a blind-date, odds are great that you know how disastrous "jumping before looking" can be. Feel free to do some online stalking here before you contact Soleer.

What We Do

"Girls only want boyfriends who have great skills." -Napoleon Dynamite

While we aren't looking to be your boyfriend and might not have "nunchuku skills," we do offer a number of other services and solutions to assist your organization.

What We’ve Done

As we say in Texas, "This ain't our first rodeo." Take a look at a sampling of some of our masterpieces, from logo design and brochure creation to webpage design and online community development.