Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty array elements with array_filter with a callback function

Tags:

php

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 ?

like image 316
Toto Avatar asked Sep 03 '10 12:09

Toto


People also ask

How do you remove empty elements from an array?

In order to remove empty elements from an array, filter() method is used. This method will return a new array with the elements that pass the condition of the callback function. array.

How do you clear an array in PHP?

Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );

What is Array_filter PHP?

Definition and Usage. The array_filter() function filters the values of an array using a callback function. This function passes each value of the input array to the callback function. If the callback function returns true, the current value from input is returned into the result array.


1 Answers

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.

like image 110
Gumbo Avatar answered Oct 22 '22 09:10

Gumbo