Tania Rascia

Skip Navigation
Removing an item from an associative array in PHP by value

Removing an item from an associative array in PHP by value

 /  6 responses

Recently, I was working with some JSON decoded into a PHP array, and I needed to remove an item from the associative array. With only the value, I wasn’t sure how to remove it, and here was the code I used.

foreach($arr['category'] as $key => $value) {
	if (in_array('item_to_remove', $value)) {
		unset($arr['category'][$key]);
	}
}

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion

  • Radek says:

    if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
    }

  • apit john says:

    Thank you

  • Matt says:

    Another way to accomplish the same result:

    unset($arr[“category”][array_flip($arr[“category”])[“item_to_remove”]]);

    • G says:

      Don't do this. Completely unreadable, if you need to make a change you're going to be kicking yourself for being an idiot and not writing reusable code.

  • Ryan says:

    Thanks for sharing, but careful with in_array() – it uses loose comparison by default meaning it does not check types and would therefore be very possible to accidentally remove an item from your array.

    For example:

    null == false // true
    false == 0 // true
    ‘apple’ == true // true
    ‘banana’ == 0 // true
    125 == true // true
    [] == false // true
    [ ‘cherry’ ] == true // true

    The solution is to pass true as the third param:

    in_array( ‘item_to_remove’, $value, true );

    One more thing – it isn’t exactly the same as it creates a new array, but array_filter() is useful for this sort of thing as well:

    $arr[‘category’] = array_filter( $arr[‘category’], function( $value ) {
    return ! in_array( ‘item_to_remove’, $value, true );
    } );

  • viki govic says:

    Thank you i really Appricate your Quality content.