I think, therefore I am. I am, therefore I sail

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

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


Add or Update your vSphere or ESXi license key through the terminal


Working from Planet Hollywood in Las Vegas

1 Comment

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

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


Powered by WordPress & Beards