USE keyword in php anonymous function

I have found a nice use of USE keyword in php anonymous function from Erik’s blog

According to his article:

The use keyword allows you to introduce local variables into the local scope of an anonymous function. This is useful in the case where you pass the anonymous function to some other function which you have no control over.
Example:

<?php
function remove_lowest_average($arr) 
{
	$average = array_sum($arr) / count($arr);

	return array_filter($arr, function($v) use ($average) {
		return ($v > $average);
	});
}

/*
following is an array with 9 elements which sum up to 45. 
Average value is 5. 
So value <= 5 will be omitted.
*/
$input = array(1,2,3,4,5,6,7,8,9);
print_r(remove_lowest_average($input));
// Output: array(6,7,8,9);
?>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s