Search code examples
phparray-filter

PHP array_filter: if array doesn't have my value return array without changes


To filter an array by key value I do this

//$Myitems this is an array
$make = '3';
$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
    $extra_fields_decode = json_decode($Myitems['extra_fields'], true);
    $main_value = $extra_fields_decode['1']['value'];
    return $main_value == $make;
})

Everything works correctly. But I want to make a condition: if my key value ($make) is not in the array, so that the array is returned without filtering. To return the original array $Myitems. Because next I want to do other things with it. I want to apply array_slice. Exemple:

$FirstItem = array_slice($Myitems, 0, 1);

To begin with, I tried to simply return the original array back like this. But it doesn't work.

$MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
    $extra_fields_decode = json_decode($Myitems['extra_fields'], true);
    $main_value = $extra_fields_decode['1']['value'];
    if ($main_value) {
        return $main_value == $make;
    } else {
        return $Myitems;
    }
})

How can this problem be solved?


Solution

  • Don't do this in the array_filter() callback. If $make is not in the array, the result of the filter will be an empty array. Check for that and use the original array instead.

    $MyfilterMain = array_filter($Myitems, function($Myitems) use($make) {
        $extra_fields_decode = json_decode($Myitems['extra_fields'], true);
        $main_value = $extra_fields_decode['1']['value'];
        return $main_value == $make;
    });
    if (count($MyfilterMain) == 0) {
        $MyfilterMain = $Myitems;
    }