The variable $id isn't in the scope of the function. You need to use the use clause to make external variables accessible:

$foo = array_filter($bar, function(id) {
    if (isset($obj->foo)) {
        var_dump(obj->foo == $id) return true;
    }
    return false;
});

See documentation for Anonymous functions (Example #3 "Inheriting variables from the parent scope").

Answer from Barmar on Stack Overflow
🌐
PHP
php.net › manual › en › function.filter-var-array.php
PHP: filter_var_array - Manual
filter_input_array() - Gets external variables and optionally filters them
🌐
Stetsenko
stetsenko.net › 2012 › 02 › php-array_filter-with-arguments
Alex Stetsenko » PHP: array_filter() with arguments
// some array $a = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // threshold to filter array elements $p = 5; // method of this class can be uses as a callback function class Filter { private $threshold; function __construct($threshold) { $this->threshold = $threshold; } function isLower($i) { return $i < $this->threshold; } } $r = array_filter($a, array(new Filter($p), 'isLower')); print_r($r);
🌐
BCCNsoft
doc.bccnsoft.com › docs › php-docs-5.6.3-en › function.filter-input-array.html
Gets external variables and optionally filters them
An array value will be FALSE if the filter fails, or NULL if the variable is not set. Or if the flag FILTER_NULL_ON_FAILURE is used, it returns FALSE if the variable is not set and NULL if the filter fails. ... <?php error_reporting(E_ALL | E_STRICT); /* data actually came from POST $_POST = array( 'product_id' => 'libgd<script>', 'component' => '10', 'versions' => '2.0.33', 'testscalar' => array('2', '23', '10', '12'), 'testarray' => '2', ); */ $args = array( 'product_id' => FILTER_SANITIZE_ENCODED, 'component' => array('filter' => FILTER_VALIDATE_INT, 'flags' => FILTER_REQUIRE_ARRAY, 'option
Top answer
1 of 2
6

The scope of the variables inside an anonymous function is ONLY within the anonymous function.

You need to inherit the variable from the parent scope. You can find more details about it in the PHP Documentation about anonymous functions (Example #3)

which would transform this line:

$filtered = array_filter($json, function (q) {

into this:

$filtered = array_filter($json, function (q, $val) {
2 of 2
2

Add another variable in use:

$filtered = array_filter($json, function (q, $key) {
                if (stripos(val], $q) !== false) {
                    return true;
                } else {
                    return false;
                }
            });

EDIT:

One of good explanations can be found here: https://teamtreehouse.com/community/variable-functions-vs-php-closures

...the benefit of a lambda is that it exists only as long as the variable it is assigned to has a reference. So the way PHP manages memory is by reference counting. Essentially, the PHP engine reads all the files it needs in order to execute the program, and while doing so it finds all the variables used and keeps a tally of how many times they are used( reference count). While the script is being executed each time the variable is used it subtracts one from the reference count. Once the reference count hits zero, the variable is deleted (more or less). Normally, a function is loaded into memory and stays there for the entire execution of the script. However, a lambda can be deleted from memory once the reference count of its variable hits zero.

A closure on the other hand is an anonymous function that encapsulates a part of the global scope at the time it is created. In other words, you can pass a variable to a closure using the "use" keyword and that variable's value will be the same as it was when the closure was created regardless of what happen's outside the closure...

Basically use keyword is needed in order to created isolated scope for variables. Without it You wouldn't be able to inject any additional variable to the function.

🌐
W3Schools
w3schools.com › php › func_filter_input_array.asp
PHP filter_input_array() Function
<?php $filters = array ( "name" ...put_array(INPUT_POST, $filters)); ?> ... The filter_input_array() function gets external variables (e.g. from form input) and optionally filters them....
🌐
CopyProgramming
copyprogramming.com › howto › filter-array-in-php-with-passing-extra-params
Php: Using Additional Parameters to Filter PHP Arrays
May 19, 2023 - $foo = array_filter($bar, function($obj) use ($id) { Php - Use external variable in array_filter, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search.
🌐
W3Schools
w3schools.com › php › func_array_filter.asp
PHP array_filter() Function
Arrays Indexed Arrays Associative Arrays Create Arrays Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Functions PHP Superglobals · Superglobals $GLOBALS $_SERVER $_REQUEST $_POST $_GET PHP RegEx PHP RegEx Functions · PHP Form Handling PHP Form Validation PHP Form Required PHP Form URL/E-mail PHP Form Complete · PHP Date and Time PHP Include PHP File Handling PHP File Open/Read PHP File Create/Write PHP File Upload PHP Cookies PHP Sessions PHP Filters PHP Filters Advanced PHP Callback Functions PHP JSON PHP Exceptions
Find elsewhere
🌐
AlphaCodingSkills
alphacodingskills.com › php › notes › php-filter-input-array.php
PHP filter_input_array() Function - AlphaCodingSkills
The PHP filter_input_array() function gets external variables and optionally filters them. This function is useful for retrieving many values without repetitively calling filter_input().
Top answer
1 of 3
12

You have at least two options:

  1. Globalize the desired variable, and then reference it inside the callback
  2. Wrap the score calculation logic with a function, then reference it inside the callback

Globalize the Variable

<?php
global $score;
$score = 42; //Some crazy calculation I don't want to repeat.

function add_score_to_title($title) {
    global $score;
    return 'Quiz Results (' . $score . '/') - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

Wrap the Score Calculation

If you only ever need the score calculation inside the filter, pull the logic into the callback itself:

<?php
function add_score_to_title($title) {
    $score = 0;
    $questions = get_quiz_result_questions();
    $total_questions = 0;
    foreach( $questions as $question ) {
        $order = $question->order;

        if( $order >= 100 ) {
            break;
    }

    if( $question->correct == $_POST['Q'][$order] ) {
        $score++;
    }
    $total_questions++;

    return 'Quiz Results (' . $score . '/') - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

Better yet, you could wrap your score calculation in a function of its own, and then call that function inside your callback:

<?php
function wpse48677_get_score() {
    $score = 0;
    $questions = get_quiz_result_questions();
    $total_questions = 0;
    foreach( $questions as $question ) {
    $order = $question->order;

    if( $order >= 100 ) {
        break;
    }

    if( $question->correct == $_POST['Q'][$order] ) {
        $score++;
    }
    $total_questions++;
    $output['score'] = $score;
    $output['total_questions'] = $total_questions;

    return $output;
}

function add_score_to_title($title) {

    $score_results = wpse48677_get_score();

    $score = $score_results['score'];

    return 'Quiz Results (' . $score . '/') - ' . $title;
}

add_filter( 'aioseop_title_single', 'add_score_to_title');
?>

If you find you have problems referencing the $_POST object, you can also register your query variable and then use get_query_var() internally to get data:

function add_score_query_vars( $query_vars ) {
    $query_vars[] = 'Q';

    return $query_vars;
}
add_filter( 'query_vars', 'add_score_query_vars' );

With this in place, $_POST['Q'] can be replaced with get_query_var('Q').

2 of 3
4
function add_score_to_title($title = false) {
  static $score = false;

  if($score === false){
    // do calc
  }

  // plugin call (filter)   
  if($title !== false)
    return 'Quiz Results (' . $score . ') - ' . $title;

  // your call
  return $score;
}

Call the function anywhere in your script to get the score, it will only be calculated once.

Another way, using anonymous functions:

// do the calc
$score = 'xxx';

add_filter('aioseop_title_single', function($title) use($score){
  return 'Quiz Results (' . $score . ') - ' . $title;  
});
🌐
Docs
doc.docs.sk › php › function.filter-input-array.html
PHP Manual - Gets external variables and optionally filters them • doc.Docs.sk
array(6) { ["product_id"]=> array(1) ... ["testscalar"]=> bool(false) ["testarray"]=> array(1) { [0]=> int(2) } } filter_input() - Gets a specific external variable by name and optionally filters it...
🌐
DEV Community
dev.to › gbhorwood › php-tame-arrays-with-map-filter-and-reduce-1h4j
php: tame arrays with map, filter and reduce - DEV Community
January 17, 2023 - at last, we get to array_filter(). the interesting part here is our callable function. it accepts one argument, $person, which is the element of our input array that we're testing. it also calls use() to add two more variables to our function's scope so we can use them in the function body.
🌐
Stack Overflow
stackoverflow.com › questions › tagged › array-filter
Recently Active 'array-filter' Questions - Stack Overflow
I have a script which allows me to filter an entire multidimensional array according to a string. But it will only work if a value of the array matches the string exactly while I would like it to work ... ... I am comparing two arrays for matched items but I need to make them case insensitive. here is the code: credit for this code to @PatrickRoberts here const words = ['word1', 'word2', 'word3'] const ... ... I want to implement a fuzzy search. I use fuse.js for this.
🌐
PHP Tutorial
phptutorial.net › home › php tutorial › php filter_input function
PHP filter_input Function
April 7, 2025 - The PHP filter_input() function allows you to get an external variable by its name and filter it using one or more built-in filters. Here’s the syntax of the filter_input() function: filter_input ( int $type , string $var_name , int $filter = FILTER_DEFAULT , array|int $options = 0 ) : mixedCode ...
🌐
Mark Baker's Blog
markbakeruk.net › 2017 › 03 › 12 › closure-binding-as-an-alternative-to-use-variables
Closure Binding as an alternative to “use” variables | Mark Baker's Blog
March 12, 2017 - And by giving our filter class and method appropriate and meaningful names, our callback is as easy to read and understand as the original Anonymous function that we used at the beginning of this article (if not more so), and our values are directly visible within the array_filter() call again; but we’ve also created a Closure that is flexible (it can accept arguments that have been calculated or derived from user input) and can be reused elsewhere in our code, passing the argument values whenever we need to call it. ... Like Loading... This entry was posted in PHP and tagged Anonymous, Binding, Closure, PHP.