2
\$\begingroup\$

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 => $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' => array(
 'q' => 'alkflsdj',
 'x' => 1,
 9 => 'm'
 ),
 'news' => 7
);
$filter = array(
 'page' => array(
 9
 ),
 'news'
); 
$result = array_mask($source, $filter);
var_dump($result);

Result:

array
 'page' => 
 array
 9 => string 'm' (length=1)
 'news' => int 7
asked Nov 14, 2012 at 6:21
\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

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 => $value)
 if (is_array($value))
 $source[$key] = array_mask($source[$key], $filter[$key]);
 return $source;
}
$source = array(
 'page' => array(
 'q' => 'alkflsdj',
 'x' => 1,
 9 => 'm'
 ),
 'news' => 7
);
$filter = array(
 'page' => array(
 9 => ''
 ),
 'news' => ''
);
var_dump (array_mask($source, $filter));
answered Nov 14, 2012 at 12:48
\$\endgroup\$
1
  • \$\begingroup\$ I had this idea, but for some reason she didn't like. Now like normal. \$\endgroup\$ Commented Nov 14, 2012 at 17:20
0
\$\begingroup\$

Looks good to me, but you can make a small optimization:

change this

 if (array_search($key, $filter) !== false){
 continue;
 }
 unset($source[$key]);

to

 if (array_search($key, $filter) === false){
 unset($source[$key]);
 }
Jeff Vanzella
4,3182 gold badges24 silver badges33 bronze badges
answered Nov 14, 2012 at 10:42
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Just a suggestion, you might want to explain why you are suggesting the change. Doing so will greatly increase the value of this answer. \$\endgroup\$ Commented Nov 14, 2012 at 17:01

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.