Search code examples
phpcallbackarray-filter

Why this array_filter method not calling this function?


private static function returnSameElementIfNotEmpty($item) {
    if (empty($item)) {
        return false;
    }
    else{
        return true;
    }
}


public static function clean($array) {
    return array_filter($array, 'returnSameElementIfNotEmpty');
}

When I try running this with a sample array I get:

Warning: array_filter() expects parameter 2 to be a valid callback, function 'returnSameElementIfNotEmpty' not found or invalid function name in C:\Framework\ArrayMethods.php on line 27


Solution

  • Try this:

    return array_filter($array, array(__CLASS__, 'returnSameElementIfNotEmpty'));
    

    The error occures because you don't call the class method. But just a function with that name. In the above example I use CLASS as the class type to access the static function returnSameElementIfNotEmpty.