Reputation: 6852
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?
Upvotes: 10
Views: 33152
Reputation: 4334
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).
Upvotes: 11
Reputation: 425
you can use:
foreach($array as $key => $item) {
if ($item['id'] === $value) {
unset($array[$key]);
}
}
Upvotes: 1
Reputation: 41810
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; });
Upvotes: 15