Fane
Fane

Reputation: 2076

Correct syntax for php array_filter?

Here is my code, throwing an error with Warning: Missing argument 2 for {closure}() in the first line

$all_together = array_filter($info,function($each_one,$extra){
    
    $op = $each_one["something"];
    
    if($op <= $extra) return $each_one["what_I_need"];
    
});

I need to use the $extra argument, independent of the input array elements. What am I missing exactly?

Upvotes: 2

Views: 1102

Answers (2)

pavlovich
pavlovich

Reputation: 1942

Seems like missing use keyword. Try this:

$all_together = array_filter($info, function($each_one) use ($extra) {
    $op = $each_one["something"];
    if($op <= $extra) return $each_one["what_I_need"];
});

Upvotes: 2

thepiyush13
thepiyush13

Reputation: 1331

As far as I know, array filter should be used like this:

<?php
function test_odd($var)
{
return($var & 1);
}

$a1=array("a","b",2,3,4);
print_r(array_filter($a1,"test_odd"));
?>

Now only each element of the specified array will be passed to the function, if you must pass another argument, supply a default value to that argument in your function definition.

Upvotes: 0

Related Questions