Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing array key from multidimensional Arrays php

I have this array

 $cart= Array(
      [0] => Array([id] => 15[price] => 400)
      [1] => Array([id] => 12[price] => 400)
    )

What i need is to remove array key based on some value, like this

$value = 15;

Value is 15 is just example i need to check array and remove if that value exist in ID?

like image 690
Miomir Dancevic Avatar asked Apr 18 '16 18:04

Miomir Dancevic


People also ask

How to remove multiple elements by key in PHP array?

How to Remove Multiple Elements by Key in PHP Array? Feb 11, 2021Editorial Staff Share Tweet Share Today’s article, we will remove multiple elements by key in a PHP array. Using PHP we can delete multiple keys from an Array. In PHP there is no built in method to achieve this, but we can combine several PHP functions to achieve this.

How to remove duplicates from the flatten array in PHP?

Removing duplicates from the flatten array is simple and we have a built-in function for it. The array_unique function removes duplicates from the one-dimensional array. we gonna use array_unique function along with array_map , serialize and unserialize to remove duplicates from the multidimensional PHP array.

What are multidimensional arrays in PHP?

For this, we have multidimensional arrays. A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

How to delete an element from an array in Python?

The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array. After removal the associated key and value does not change. Parameter: This function accepts single parameter variable.


2 Answers

array_filter is great for removing things you don't want from arrays.

$cart = array_filter($cart, function($x) { return $x['id'] != 15; });

If you want to use a variable to determine which id to remove rather than including it in the array_filter callback, you can use your variable in the function like this:

$value = 15;
$cart = array_filter($cart, function($x) use ($value) { return $x['id'] != $value; });
like image 104
Don't Panic Avatar answered Sep 20 '22 15:09

Don't Panic


There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops...

$value = 15;
foreach ($cart as $i => $v) {
    if ($v['id'] == $value) {
        unset($cart[$i]);
    }
}

If $value is not in the array at all, nothing will happen. If $value is in the array, the entire index will be deleted (unset).

like image 34
kainaw Avatar answered Sep 23 '22 15:09

kainaw