0
$cart_array = .....;

Array
(
[0] => item Object([id] => 123 [size_id] => 2)
[1] => item Object([id] => 123 [size_id] => 3))



$cart_array = array_filter(
    $cart_array,
    function ($item) {
        return $item->id != 123 && $item->size_id != 2;
    }
);

Expected result :

Array
    (
    [0] => item Object([id] => 123 [size_id] => 3))

But this returns an empty array($cart_array). Any help would be appreciable.Thank you.

1
  • 1
    Can you share the result you're trying to get? Commented Jun 11, 2017 at 4:57

2 Answers 2

2

This is because both items in $cart_array fail the test.

<?php

$cart1 = new StdClass;
$cart1->id = 123;
$cart1->size_id = 2;

$cart2 = new StdClass;
$cart2->id = 123;
$cart2->size_id = 3;

$cart_array = array_filter(
    [$cart1, $cart2],
    function ($item) {
        // Items both have an id of 123, therefore this returns false
        return $item->id != 123 && $item->size_id != 2;
    }
);

Maybe you wanted to just keep size 3?

$cart_array = array_filter(
    [$cart1, $cart2],
    function ($item) {
        // This will keep $cart2 since it has an id of 123 and a size_id not equal to 2 but remove $cart1 since size_id is equal to 2
        return $item->id == 123 && $item->size_id != 2;
    }
);

Example here: http://ideone.com/oqz16S

Sign up to request clarification or add additional context in comments.

7 Comments

But it does not work with below scenario. ideone.com/eK2BMP What if I need to remove $cart3 ??
It still works fine for me: ideone.com/aJ6X6w, this only keeps $cart2 because size_id fails on $cart1 and id fails on $cart3.
$cart3 id is 124.
Do you want to keep $cart3 or remove it? My code removes it and your comment above asked what to do if you want to remove it.
what I only need is to remove the given item which is related to "id" and "size_id" keep the rest .
|
0

What is the result if you print_r your array? If the the code you've put in your question is identical to the code you're trying to run, one of your issues is there is no comma (,) between your array items, and there needs to be. Like so:

Array
(
[0] => item Object([id] => 123 [size_id] => 2),
[1] => item Object([id] => 123 [size_id] => 3)
)

I'm not familiar with the 'item Object(...' syntax you're using, so I won't be of much help past what I've already said.

Also, like the answer above, your test excludes both objects because id on both is 123.

Comments

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.