1

I'm trying to use the code from answer to this question: Count values in subarray

But it doesn't want to work with variables?

So for instance, this works:

echo count(array_filter($tasks, function($element){
    return $element['parent'] == 15;
}));

Echoes out: 4

But this fails:

$number = 15;

//Kolla ifall denna har subtasks?
echo count(array_filter($tasks, function($element) {
    return $element['parent'] == $number;
}));

Echoes out 0

Any ideas as to why?

Community
  • 1
  • 1
Alisso
  • 1,861
  • 1
  • 17
  • 32

1 Answers1

1

Because $number is not available inside the lambda function, add use ($number):

$number = 15;
//Kolla ifall denna har subtasks?
echo count(array_filter($tasks, function($element) use ($number) {
return $element['parent'] == $number;
}));
AndreKR
  • 32,613
  • 18
  • 106
  • 168
  • You might also want to consider handing the variable `$number` over as a function argument. That makes the code easier to understand. – arkascha Oct 16 '12 at 09:51
  • I don't think `array_filter()` can do that and I don't think that it will make it any easier either. For PHP 5.2 there is an ugly workaround here: http://stackoverflow.com/questions/5482989/php-array-filter-with-arguments – AndreKR Oct 16 '12 at 09:52