3

I am trying to compare a value inside an array, that is initialized before array_filter is called.

The array is not empty but becomes equal to null when the control flows inside the callback function of array_filter. What could be the reason for this?

$stream = $stream_list[$i]['@attributes']; // IS ARRAY

$chargeable_feature = array_filter($applicable_conversions,function($conversion) {
     return $conversion['FeatureName'] == $stream['FeaturesUsed'];
     // STREAM BECOMES NULL HERE
});
Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

2 Answers2

3
$stream = $stream_list[$i]['@attributes']; // IS ARRAY

$chargeable_feature = array_filter($applicable_conversions,function($conversion) use ($stream) {
     return $conversion['FeatureName'] == $stream['FeaturesUsed'];
});
Vuer
  • 149
  • 6
  • 2
    Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Rizier123 Aug 24 '16 at 11:52
2

You can't use $stream inside the function, it's in a different scope.

Consider using the use construct:

$chargeable_feature = 
array_filter($applicable_conversions,function($conversion) use ($stream) { ...

Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name.

Closures may inherit variables from the parent scope. Any such variables must be passed to the use language construct.

And note the difference between use and global variable scope:

Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701