How to Fix PHP array_filter Removing Valid Falsy Values
In this tutorial, you'll learn about How to Fix PHP array_filter Removing Valid Falsy Values. We cover key concepts, practical examples, and best practices.
The Problem
Fix PHP array_filter removing legitimate values like 0, empty string, or false when no callback is used — without proper handling, this issue causes subtle bugs that are hard to trace in production.
Quick Fix
Wrong Code
// WRONG — this approach triggers the php-array-filter error
<?php
$ratings = [4, 0, 3, 5, 0, 2];
$filtered = array_filter(\$ratings);
print_r(\$filtered);
Wrong Output
Array ( [0] => 4 [2] => 3 [3] => 5 [5] => 2 )
// Zero ratings removed — they are valid data!
Right Code
// RIGHT — corrected implementation
<?php
\$ratings = [4, 0, 3, 5, 0, 2];
\$filtered = array_filter(\$ratings, fn(\$v) => \$v !== null);
print_r(\$filtered);
\$data = ['a' => 1, 'b' => 0, 'c' => 3];
\$keys = array_filter(\$data, fn(\$k) => \$k !== 'b', ARRAY_FILTER_USE_KEY);
print_r(\$keys);
Right Output
Array ( [0] => 4 [1] => 0 [2] => 3 [3] => 5 [4] => 0 [5] => 2 )
Array ( [a] => 1 [c] => 3 )
Prevention
- Always provide a callback when zero, empty string, or false are valid values
- Use ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH for key-based filtering
- Without callback, array_filter removes: false, null, 0, 0.0, '', '0', []
- Use array_values to re-index the result if sequential keys are needed
Common Mistakes with array filter
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world PHP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro