29

I just came across this code:

array_filter(array_map('intval', $array));

It seems to return all entries of $array converted to int where the number is > 0.

However, I can't see on the manual page that this is defined. It is supposed to return the array value if the callback function evaluates to true. But there isn't any callback function defined here.

Confusing is also that the callback function is optional on the manual page.

3
  • 2
    array_filter usually just removes empties (or equivalent) in your array if no callback. Commented Oct 19, 2014 at 21:57
  • 4
    This is extracted from manual If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed. Commented Oct 19, 2014 at 21:59
  • Yes, cheers, I overlooked it Commented Oct 19, 2014 at 22:00

2 Answers 2

41

Removes empty or equivalent values from array:

$entry = array(
    0 => 'foo',
    1 => false,
    2 => -1,
    3 => null,
    4 => '',
    5 => 0
);
    
print_r(array_filter($entry));

Result

Array
(
    [0] => foo
    [2] => -1
)

See the original documentation from the manual: Example #2 array_filter() without callback

Sign up to request clarification or add additional context in comments.

2 Comments

What is the merit of the approved suggested edit (not a rhetorical question)?
@PeterMortensen I have added a 0 to the $entry array to show that array_filter($entry) function also filters(removes) the value 0 (besides false, null and empty string ' ')
12

If you read just a little further on the page to which you linked, you find, "If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.