Reputation: 205
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);
}
Upvotes: 2
Views: 41
Reputation: 3780
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
Upvotes: 3
Reputation: 10469
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);
}
Upvotes: 2