Search code examples
phparraysarray-filter

Cannot call variable outside array_filter()


Why i cannot call variable outside array_filter(), this my code

class JsonSelect
{
    public function jsonSource($jsonSource, $val){

        $file_contents = file_get_contents($jsonSource);

        if(!$file_contents){
            throw new Exception('Invalid file name');
        }

        $json = json_decode($file_contents, true);
        $q = $_POST['q'];
        $filtered = $json;

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

        echo json_encode(array_slice(array_values($filtered), 0, 20));
    }
}

and this my picture to describe my problem. parameter $valcannot be called inside $key[$val] enter image description here


Solution

  • 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 ($key) use ($q) {
    

    into this:

    $filtered = array_filter($json, function ($key) use ($q, $val) {