Reputation: 2598
$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.
Upvotes: 0
Views: 50
Reputation: 1284
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.
Upvotes: 0
Reputation: 3536
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
Upvotes: 2