0

I'm trying to remove arrays in array who contain specific keys.

I would like to remove arrays who contain :

[code] => 404
[message] => The exhibitor has no validated order.

Example :

Array
(
    [0] => Array
        (
            [id] => 2924
            [id_dossier] => 26169
        )

    [1] => Array
        (
            [code] => 404
            [message] => The exhibitor has no validated order.
        )

    [2] => Array
        (
            [code] => 404
            [message] => The exhibitor has no validated order.
        )

    [3] => Array
        (
            [id] => 3469
            [id_dossier] => 27831

        )
)

And I would like output like this :

Array
(
    [0] => Array
        (
            [id] => 2924
            [id_dossier] => 26169
        )
    [1] => Array
        (
            [id] => 3469
            [id_dossier] => 27831

        )
)

I tried with : array_filter :

 $final_array = array_filter($final_array, function ($var) {
        return $var['code'] != '404';
    });

And I tried with a foreach :

foreach ($final_array as $thisArrIndex=>$subArray) {
    if ($subArray['code'] == "404" ) {
        unset($final_array[$thisArrIndex]);
    }
}

My output is good but I got a notice :

Notice : Undefined index: code in .....

What's wrong please ? Thank you in advance

Jandon
  • 605
  • 7
  • 32
  • Your notice is due to `Array( [id] => 2924, [id_dossier] => 26169)` for exemple, because it doesn't have a `code` index, you could use test `isset($var['code'])` which return `true` if `code` index exist – ekans Sep 13 '21 at 14:25
  • Thank you for your answer. Where can I add this condition to know if `code` exist? I must use `unset` after ? – Jandon Sep 13 '21 at 14:39
  • 1
    you can add it in `array_filter` condition, something like this : `return !isset($var['code']) || $var['code'] != '404';` and you don't need to `unset` it because these entry will be filtered by function ;) – ekans Sep 13 '21 at 14:41
  • 1
    `return ($var['code'] ?? '') != 404` You can also use the null coalescing operator if you like. – Don't Panic Sep 13 '21 at 14:46

0 Answers0