- using
array_filter
without callback function:
In PHP, the array_filter function is used to filter elements of an array using a callback function. However, if no callback function is provided, it will filter out falsy values by default. Behavior of array_filter($categoryIds) without a callback
If array_filter is used without a callback, it removes elements that evaluate to false in a Boolean context. Specifically, it filters out:
false
0 (integer and string "0")
null
"" (empty string)
[] (empty array)
Example:
$categoryIds = [1, 2, null, 0, '', '3', false, [], 5];
$result = array_filter($categoryIds);
print_r($result);
output:
Array
(
[0] => 1
[1] => 2
[5] => 3
[8] => 5
)
Notice that null, 0, "", false, and [] have been removed.
Important Notes:
Keys are preserved – The resulting array retains the original keys. If you need re-indexing, you can use array_values($result).
If a callback is provided, array_filter will keep elements for which the callback returns true.