0

Works: returns [false,null]

array_filter([1, 2, 3, false, null], function($value) {
   return empty($value);
});

Does not Work:

array_filter([1, 2, 3, false, null], empty); // syntax error, unexpected ')',expecting '('

Why cant i just pass in the function as an argument?

1

3 Answers 3

2

What is empty meant to be in your second example?

Note that php's "empty" is not a function, but a language construct. Therefore you cannot use it as a function. That is explained in the documentation: http://php.net/manual/en/function.empty.php (Scroll down to the "Notes" section...)

That explains why the first variant does work, whilst the second results in a syntax error.

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

Comments

2

Functions can be passed into any function/method that takes a callable argument. However, empty (), in spite of how it's written in code, is not a function. It's a language construct.

If you want to pass empty as a callable, you have no choice but to wrap it in a user-defined function.

$func = function ($param) { return empty ($param); };

print_r (array_filter ([1,2, NULL, 3, 4, FALSE, 5, 6, 0, "", 7, 8, 9], $func));

or

print_r array_filter (([1,2, NULL, 3, 4, FALSE, 5, 6, 0, "", 7, 8, 9], function ($param) { 
    return empty ($param); 
}));

Other language constructs are affected as well, so you might want to consult the manual for a list of language constructs (all the ones that terminate with () like functions are things you can't use with functions that take a callable argument).

http://php.net/manual/en/reserved.keywords.php

Comments

1

empty() is not a function, it's a language construct. array_filter expects a callable as the second argument. You will need to use a wrapper function exactly as you have in your first example:

array_filter([1, 2, 3, false, null], function($value) {
   return empty($value);
});

5 Comments

If this does not work, according to your own statement (which is true), then why do you post it as an "answer"?
Because the question was "Why cant i just pass in the function as an argument?"
Yes, true, still this "answer" is very confusing. Stating that this will not work is fine and good, giving a non-working example is a very bad style in my eyes...
You are right, I'll clarify - thank you.
Apart from that the version without quotes would come out the same, since php would assume the non defined constant was meant as a string. So you would get exactly the same result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.