Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isset() not allowed as callback for array_filter()

Tags:

php

If you want to remove null values from an array, then passing them through a simple array_filter() and using the built in isset() function seems like a great option:

$dairyFree = true;
$toppings = [
 'tomato',
 'oregano',
 'pepperoni',
 ($dairyFree) ? null : 'cheese',
];

$toppings = array_filter($toppings, 'isset');

Pretty simple, but using isset() in array_filter() raises the following warning:

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

It is easy enough to wrap the same code inside a closure, but my question is – why would php balk at the isset() function and not other internal functions like strlen()?

like image 662
jpschroeder Avatar asked Dec 15 '16 16:12

jpschroeder


1 Answers

The isset is not exactly a function, it is a construct like echo. If you are just looking for removing null values from the array, without isset parameter is good enough.

<?php
    $dairyFree = true;
    $toppings = [
      'tomato',
      'oregano',
      'pepperoni',
      ($dairyFree) ? null : 'cheese',
    ];
    $toppings = array_filter($toppings);
    print_r($toppings);
?>

This outputs:

Array
(
    [0] => tomato
    [1] => oregano
    [2] => pepperoni
)
like image 87
Praveen Kumar Purushothaman Avatar answered Sep 20 '22 09:09

Praveen Kumar Purushothaman