0

I have this little function to filter my array by keys:

 private function filterMyArray( )
 {
      function check( $v )
      {
           return $v['type'] == 'video';
      }
      return array_filter( $array, 'check' );
 }

This works great but since I have more keys to filter, I was thinking in a way to pass a variable from the main function: filterMyArray($key_to_serch) without success, also I've tried a global variable, but seems not work.

Due some confusion in my question :), I need something like this:

 private function filterMyArray( $key_to_serch )
 {
      function check( $v )
      {
           return $v['type'] == $key_to_serch;
      }
      return array_filter( $array, 'check' );
 }

Any idea to pass that variable?

1
  • mmm ... nested functions ... not pretty, especially when php provides functions that do this for you. try array_map() or array_filter() with lambda/closure Commented Dec 9, 2011 at 1:40

4 Answers 4

3

This is where anonymous functions in PHP 5.3 come in handy (note the use of use):

private function filterMyArray($key)
{
     return array_filter(
         $array,
         function check($v) use($key) {
             return $v['type'] == $key;
         }
     );
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is where identation comes in place: this code is very hard to understand (for me) if it's not properly indented. I've just modified identation, roll back if you think yours is easier to read
0
private function filterMyArray($key_to_search) {
  function check( $v ) {
       return $v[$key_to_search] == 'video';
  }
  return array_filter( $array, 'check' );
}

should work because the inner function has access to the variables in the outer function

Comments

0

You need to use the use keyword to get the variable in scope, c.f. this example in php's doc.

Comments

-1

Here's a PHP < 5.3 version using create_function.

private function filterMyArray( $key)
{
      $fn = create_function( '$v', "return $v[$key] == 'video';");
      return array_filter( $array, $fn);
}

1 Comment

Actually, this will not work because the dollar signs inside the double-quoted string will be seen as variable references.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.