0

I have and array:

Array(
  [9533]=>44
  [6478]=>56
)

I want to filter the array with a variable. I have tried this:

function filterArray($value){
    return ($value == $myVar);
}

$filteredArray = array_filter($myArray, 'filterArray');
print_r($filteredArray);

it just prints:

array()

if I change the variable to a hard number like 44, then it will give me what I want.

Array(
  [9533]=>44
)
7
  • 2
    From where $myVar is coming? Commented Aug 13, 2012 at 21:32
  • the filterArray doesn't know what $myVar you are looking to match. Commented Aug 13, 2012 at 21:33
  • 1
    This is where closures with a "use" are particularly useful: $myVar = 44; $filteredArray = array_filter($myArray, function($value) use ($myVar) { return $value == $myVar; } ); Commented Aug 13, 2012 at 21:34
  • You probably want to declare global $myVar; in the beginning of filterArray() Commented Aug 13, 2012 at 21:34
  • 2
    @alfasin no please, don't incite him to use global... Commented Aug 13, 2012 at 21:35

2 Answers 2

3

Don't use globals, that's a bad idea

$myVar = 44; 
$filteredArray = array_filter( $myArray, 
                               function($value) use ($myVar) {
                                   return $value == $myVar;
                               }
                             );
Sign up to request clarification or add additional context in comments.

Comments

0

If $myVar is defined outside of the filterArray callback function, you need to declare it global within the function before you can use it. So if you change your filterArray callback to this, then it should work:

function filterArray($value){
    global $myVar;
    return ($value == $myVar);
}

DEMO

Try to avoid using the global keyword when you don't need to. For most functions you can pass the variable as an argument instead. In your case, the global is necessary since array_filter does not allow callbacks with parameters.

6 Comments

I said, no please, don't incite him to use global...
Would you like to explain why it's such a bad idea instead of just downvoting? Obviously they're considered bad practice but this really isn't a situation where it will hurt.
If he starts to learn PHP, it will be preferable that he doesn't try to use global every time he wants to retrieve a variable that isn't in the scope of the function. It will become hard and hard to maintain and understand his code. I never used global and every code I read don't use global.
Thanks for all the quick responses. I cannot declare the variable right before the function because the variable is a user input. Global works great! Please explain why I shouldnt use it.
A more detailled answer why global is evil
|

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.