Skip to content

Instantly share code, notes, and snippets.

@zahra-ove
Created February 28, 2025 08:49
Show Gist options
  • Save zahra-ove/22bb6292629c860300f1f84e3837b3a7 to your computer and use it in GitHub Desktop.
Save zahra-ove/22bb6292629c860300f1f84e3837b3a7 to your computer and use it in GitHub Desktop.
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment