Remove Empty Items From an Array in PHP
- 1 minute read
The following snippet uses PHP’s built-in array_diff function to return a new copy of a given array without any empty string values:
$arr = array('red', 'blue', '', 'yellow');
$newArr = array_diff($arr, array(''));
After the above code has executed, $newArr
will equal ['red', 'blue', 'yellow']
. Notice how the empty string value is gone.
I want to note that array_diff
should typically be used over array_filter
, because array_filter
removes any value that evaluates to false
, not just empty strings.
So in the following example, values such as 0
also get removed:
// You probably don't want to do this!
$newArr = array_filter($arr);
Conclusion
Anyway, array_diff
can serve as a simple and handy way to clean up your PHP arrays.
I hope you found this article useful!