Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

php - Array_filter and empty()

Warning: array_filter() expects parameter 2 to be a valid callback, function 'empty' not found or invalid function name....

Why is empty considered a invalid callback?

$arr = array_filter($arr, 'empty');

This works: if(empty($arr['foo'])) die();

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Answer

empty() is not a function but a language construct and array_filter() can only accept a function as its callback.

This is given as a small note on the manual page:

Note: Because this is a language construct and not a function, it cannot be called using variable functions

Work around

To work around this you can wrap empty in another function for example:

function empty_test($val) {
    return empty($val);
}

And then call it like so:

$arr = array_filter($arr, 'empty_test');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...