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
)
j0k
  • 22,600
  • 28
  • 79
  • 90
Tyler Nichol
  • 635
  • 2
  • 7
  • 28

2 Answers2

3

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

$myVar = 44; 
$filteredArray = array_filter( $myArray, 
                               function($value) use ($myVar) {
                                   return $value == $myVar;
                               }
                             );
Community
  • 1
  • 1
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
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.

Alex Kalicki
  • 1,533
  • 9
  • 20
  • I said, *no please, don't incite him to use `global`...* – j0k Aug 13 '12 at 21:44
  • 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. – Alex Kalicki Aug 13 '12 at 21:45
  • 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`. – j0k Aug 13 '12 at 21:49
  • 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. – Tyler Nichol Aug 13 '12 at 21:51
  • A more detailled answer why [`global` is evil](http://stackoverflow.com/a/5166527/569101) – j0k Aug 13 '12 at 21:53
  • @j0k the fact that we should not encourage him to use globals does not mean that you should downvote a correct answer. +1 from me! – Nir Alfasi Aug 13 '12 at 22:10