2

I'm having difficulty with variable scope. I have a function that looks up a lab value from a multidimensional array. I want to pass the function the name of the lab and have it look it up. The $lab I pass to the get_lab function however is not accessible to the second function used in the array_filter. Where am I going wrong with scope?

function get_lab($lab){
    $result = array_filter($labs_array, function($v) { 
        return $v[1] == $lab; 
    });
    print_r($result);
}

2 Answers 2

3

You should declare variable in use clause like this

function get_lab($lab){
    $result = array_filter($labs_array, function($v) use ($lab) { 
        return $v[1] == $lab; 
    });
    print_r($result);
}

Check the manual for anonymous functions

Sign up to request clarification or add additional context in comments.

Comments

2

You need to pass $lab to inner function..

One way is to use the use keyword

function get_lab($lab){
    $lab = $lab;
    $result = array_filter($labs_array, function($v) use ($lab) { 
        return $v[1] == $lab; 
    });
    print_r($result);
}

Comments

Your Answer

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.