10

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?

3 Answers 3

15

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; });
Sign up to request clarification or add additional context in comments.

1 Comment

This answer should accepted.. No one wants to use loop for a single task
11

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).

1 Comment

If replacing $a with $cart was confusing, this may be over your head.
1

you can use:

foreach($array as $key => $item) {
  if ($item['id'] === $value) {
    unset($array[$key]);
  }
}

3 Comments

I don't do that by reference because I know I will use $item later and it will take me hours to realize that $item is a reference to the last item in $array.
This cannot work, because unset($item) does not remove the array element; it only unsets the reference to it.
if you create function clearArray($value){ ... } you not need more use $item later, btw I think better solution to up with array_filter function from php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.