Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i pass a single additional argument to array_map callback in PHP?

How can i pass a single additional argument to array_map callback? In my example i'd like to pass $smsPattern (as a second argument, after current element in $featureNames) to the function array_map with $getLimit closure:

$features = $usage->getSubscription()->getUser()->getRoles();

// SMS regular expression in the form of ROLE_SEND_SMS_X
$smsPattern = '/^ROLE_SEND_SMS_(?P<l>\d+)$/i';

// Function to get roles names and X from a role name
$getNames = function($r) { return trim($r->getRole()); };
$getLimit = function($name, $pattern) {
    if(preg_match($pattern, $name, $m)) return $m['l'];
};

// Get roles names and their limits ignoring null values with array_filter
$featuresNames = array_map($getNames, $features);
$smsLimits     = array_filter(array_map($getLimit,  $featureNames, $smsPattern));

With this code i'm getting a weird warning:

Warning: array_map() [function.array-map]: Argument #3 should be an array.

Of course di reason is for reusing $getLimit closure with another regular expression like $smsPattern. Thanks.

like image 971
gremo Avatar asked Jun 03 '12 16:06

gremo


1 Answers

This is exactly what closures are about:

$getLimit = function($name) use ($smsPattern) {
    if(preg_match($smsPattern, $name, $m)) return $m['l'];
};

$smsLimits = array_filter(array_map($getLimit, $features));

If you want to generalize it to other patterns, wrap the function creation into another function:

function patternMatcher($pattern) {
    return function($name) use ($pattern) {
        if(preg_match($pattern, $name, $m)) return $m['l'];
    };
}

$getLimit = patternMatcher($smsPattern);
$smsLimits = array_filter(array_map($getLimit, $features));

And here it is wrapped up as an anonymous function:

$patternMatcher = function($pattern) {
    return function($name) use ($pattern) {
        if(preg_match($pattern, $name, $m)) return $m['l'];
    };
};

$smsLimits = array_filter(array_map($patternMatcher($smsPattern), $features));
like image 164
Emil Vikström Avatar answered Sep 19 '22 09:09

Emil Vikström