phparraysrecursionmultidimensional-arrayfilter

Recursively keep only even values in a multidimensional array


For example the given array is

$data = array(
    1,
    'alpha',
    4,
    array(
        'gamma',
        6,
        8,
        array(7, 9, 11, 90),
        22,
        60
    ),
    14,
    51,
    'beta'
);

the expected result is

array(
    4,
    array(
        6,
        8,
        array(90),
        22,
        60
    ),
    14
)

I tried this code

function getEvenValues($array, $holder = array()) {
    foreach ($array as $value) {
        if (gettype($value) == 'array') {
            getEvenValues($value);
        }
          else if(gettype($value) == 'integer'){
            if($value % 2 == 0){
              array_push($holder, $value);      
            }
        }
    }
    return $holder;
}

print_r(getEvenValues($data));

But didn't get expected result.


Solution

  • Please check bellow code:

    function getEvenValues($array, $holder = array()) {
        foreach ($array as $value) {
            if (is_array($value)) {
                array_push($holder,getEvenValues($value));
            }
             else if(gettype($value) == 'integer'){
                 if($value % 2 == 0){
                     array_push($holder, $value);      
                 }
            }
        }
        return $holder;
    }
    

    I will provide you the expected result.