Suhail Gupta Suhail Gupta - 8 months ago 23
PHP Question

Non empty array becomes null inside the callback function of array_filter

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'];


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).