Madushan Perera Madushan Perera -4 years ago 37
PHP Question

PHP removing an object from array returns empty array

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download