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()
?
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With