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

December 9, 2013

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.

$key = array_search( $needle, $haystack );
unset( $haystack[$key] );

For example, given the following array:

$colors = array( 'red', 'blue', 'green', 'yellow' );

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

$key = array_search( 'green', $colors );
unset( $colors[$key] );

Or you could change it to ‘brown’ with:

$key = array_search( 'green', $colors );
$colors[$key] = 'brown';

One thought on “PHP: Erase a value out of an array without knowing its key

  1. Tanner (December 9, 2013)

    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;
    }