array_mask, Seeking alternative code I would really love to hear your critiques on:


Code quality
Code clarity
More efficient alternative code


Code:

function array_mask(array $source, array $filter){
    foreach ($source as $key =&gt; $value){
        if (!isset($filter[$key])){
            if (array_search($key, $filter) !== false){
                continue;
            }
            unset($source[$key]);
        } else {
            if (is_array($source[$key])){
                $source[$key] = array_mask($source[$key], $filter[$key]);
            }
        }
    }
    return $source;
} 


$source = array(
    'page' =&gt; array(
        'q' =&gt; 'alkflsdj',
        'x' =&gt; 1,
        9   =&gt; 'm'
    ),
    'news' =&gt; 7
);
$filter = array(
    'page' =&gt; array(
        9
    ),
    'news'
); 

$result = array_mask($source, $filter);
var_dump($result);


Result:


array
  'page' => 
    array
      9 => string 'm' (length=1)
  'news' => int 7
You can use built-in functions instead. Like this for example:

function array_mask(array $source, array $filter)
{
    $source = array_intersect_key($source, $filter);

    foreach ($source as $key =&gt; $value)
        if (is_array($value))
            $source[$key] = array_mask($source[$key], $filter[$key]);

    return $source;
}

$source = array(
    'page' =&gt; array(
        'q' =&gt; 'alkflsdj',
        'x' =&gt; 1,
        9   =&gt; 'm'
    ),
    'news' =&gt; 7
);
$filter = array(
    'page' =&gt; array(
        9 =&gt; ''
    ),
    'news' =&gt; ''
);

var_dump (array_mask($source, $filter));