PHP: Erase a value out of an array without knowing its key

By , December 9, 2013 12:07 pm

If you find yourself with an array that you know contains a certain value that you need to access or erase here is a useful code snippet that I came across the other day.

  1.  
  2. $key = array_search( $needle, $haystack );
  3. unset( $haystack[$key] );
  4.  

For example, given the following array:

  1.  
  2. $colors = array( 'red', 'blue', 'green', 'yellow' );
  3.  

If you wanted to get rid of 'green' but are unsure of its key:

  1.  
  2. $key = array_search( 'green', $colors );
  3. unset( $colors[$key] );
  4.  

Or you could change it to 'brown' with:

  1.  
  2. $key = array_search( 'green', $colors );
  3. $colors[$key] = 'brown';
  4.  

Leave a Reply

One Response to“ PHP: Erase a value out of an array without knowing its key”

  1. Tanner says:

    Nice, thanks Ben! This is much shorter than what I’ve been using:

    foreach( $array as $key => $element ) {
    if( $element !== $needle )
    continue;

    unset($array[$key]);
    break;
    }

Theme by Blam Designs
Based on Themocracy

Add this ribbon to your WordPress website re-abolish slavery
%d bloggers like this: