Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Deleting an entry from a multidimensional array

I have an array like this:

$_SESSION['food'] = array( 

// ARRAY 1
array(
      "name" => "apple",
      "shape" => "round",
      "color" => "red"
  ),

// ARRAY 2
   array(
      "name" => "banana",
      "shape" => "long",
      "color" => "yellow"
  )
);

I want to search through all keys in all child arrays and delete the entire child array if the search term is found.

So, basically:

  1. If searching for "long", the entire Array 2 is removed.
  2. If searching for "apple", the entire Array 1 is removed.

How would I accomplish this?

Thanks!

like image 843
RCWH Avatar asked Jan 31 '26 19:01

RCWH


1 Answers

This should do the trick:

foreach ($array as $key => $value) {
    foreach ($value as $child_value) {
        if ($child_value == $search_term) {
            unset($array[$key]);
            continue 2;
        }
    }
}
like image 186
mfonda Avatar answered Feb 02 '26 11:02

mfonda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!