PHP: How to remove all falsy values from an array

Updated: January 11, 2024 By: Guest Contributor Post a comment

Introduction

In PHP, arrays are fundamental structures that are used to store collections of data. However, it’s quite common to encounter situations where an array contains a mix of ‘truthy’ and ‘falsy’ values, particularly after performing operations such as filtering data from a database or processing user input. In this tutorial, we will explore what falsy values in PHP are and look at various methods for removing them from arrays.

Understanding Falsy Values in PHP

In PHP, a falsy value is considered to be any value that is equivalent to false when evaluated in a boolean context. The following are considered falsy:

  • false
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • '' or "" (an empty string)
  • '0' (a string containing a single zero)
  • [] (an empty array)
  • null

All other values are considered ‘truthy’ in PHP and will behave as true in boolean expressions.

Why Remove Falsy Values?

There may be several reasons why you’d want to remove falsy values from your arrays. Perhaps you need to ensure that each element contains data that equates to ‘truthy’ for the correct operation of your application, or maybe you need to clear out ’empty’ values after filtering an array. Whatever the reason, PHP offers several functions that can help.

Using array_filter to Remove Falsy Values

The array_filter function is one of the easiest ways to remove falsy values from an array. The function iterates over each element of the array and applies a callback function you define. If the callback returns true, the element is included in the output array; otherwise, it is not. If you don’t provide a callback function, array_filter will simply remove all values that are equivalent to false.

$array = [0, 1, 'A string', '', false, [], null, 42];
$filtered_array = array_filter($array);
print_r($filtered_array);
// Output:
// Array
// (
//     [1] => 1
//     [2] => A string
//     [7] => 42
// )

This example demonstrates how to use array_filter without a callback function to remove all falsy values from an array.

Caveats with array_filter

While array_filter is a great tool, it has some caveats. It won’t remove all ’empty’ values by default. For instance, it does not remove ’empty’ strings from arrays with associative keys unless you explicitly tell it to.

Custom Callbacks for Specific Needs

You can define a custom callback function to pass to array_filter for more control over the filtration process. For example, you might want to remove all non-numeric values from an array:

function is_numeric_val($value) {
    return is_numeric($value);
}
$array = [0, 1, 'A string', '55.35', '0', 42, null];
$filtered_array = array_filter($array, 'is_numeric_val');
print_r($filtered_array);
// Output:
// Array
// (
//     [1] => 1
//     [3] => 55.35
//     [5] => 42
// )

In this example, the custom function is_numeric_val ensures only numeric values are included in the filtered_array.

Preserving Keys

When using array_filter, by default, the keys are preserved. This can lead to a non-sequential numeric array which may or may not be desirable depending upon your requirements. To reindex keys, you can combine array_values with array_filter:

$array = [0 => 'apple', 1 => false, 2 => null, 3 => 'banana', 4 => ''];
$filtered_array = array_values(array_filter($array));
print_r($filtered_array);
// Output:
// Array
// (
//     [0] => apple
//     [1] => banana
// )

In the above code, array_values is used to reindex the final array so that it has sequential numeric keys.

Other Options for Filtering Arrays

While array_filter is commonly used, PHP offers other functions for working with arrays that, in conjunction with other methods, can help to remove falsy values. For example, you can combine the use of array_map with array_filter:

function truthify($value) {
    return ($value) ? true : false;
}

$array = ['0', 'Real value', false, 42, '', null];
$truthy_array = array_filter(array_map('truthify', $array));
print_r($truthy_array);
// Outputs:
// Array
// (
//     [1] => 1
//     [3] => 1
// )

You can use array_map to cast all values to truthy or falsy and then filter out the falsy ones.

Conclusion

Through this guide, we’ve explored what falsy values are in PHP and various methods by which you can remove them from arrays. Whether you’re cleaning up an array post-data processing or preparing inputs for further validation, functions like array_filter and associated techniques can significantly simplify the process. Remember to consider the keys, as their preservation or restructuring may be essential depending on your context.

Final Tips

When dealing with arrays, always be clear about your intentions with array keys, as most array functions offer both value and key integrity options. Also, while PHP’s array functions are powerful, overusing them without understanding your data can lead to performance issues. Use functions purposefully and test the performance implications if you’re dealing with large datasets.

With these skills and considerations, you’re well-equipped to tackle any array-cleaning challenges the world of PHP throws your way. Happy coding!