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?
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.
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.
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.
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.
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; });
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With