9

I'm trying to delete empty elements in an array with the function array_filter.

When i use an external callback like this :

function callback($a) { return !empty($a);}
$arr = array("abc",'','ghi');
$res = array_filter($arr, "callback");

it works as expected.

But if i use array_filter like that :

$arr = array("abc",'','ghi');
$res = array_filter($arr, function($a) { return !empty($a);});

It fails with the error :

PHP Parse error:  syntax error, unexpected T_FUNCTION in test.php on line 2

What am i doing wrong ?

0

2 Answers 2

15

It seems that you’re using a PHP version that does not support anonymous functions (available since PHP 5.3.0).

But array_filter does already filter empty values if you don’t specify a callback function:

If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.

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

1 Comment

Just a note that without a callback and input like $arr = array("abc",'','ghi', ' '); the last item will not be filtered out since array_filter will not trim the input.
0

It works well with PHP5. Check your PHP version, and upgrade if necessary.

1 Comment

I have php 5.1.6 and can't upgrade :-(

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.