Removing Empty Array Keys in PHP
TIL how to remove empty array keys that don't hold any value, e.g. when passing multiple query parameters in an array via GET, the
array_filter function will help to clean your array.
array_filter — Filters elements of an array using a callback function […]
Iterates over each value in the array passing them to the callback function. […]
If no callback is supplied, all empty entries of array will be removed.
In its simplest form, suitable for the use case from above, the
array_filter function looks like this:
$params = ; $params = $_GET( $params ); $params = array_filter( $params );
This code will return the array with only the keys that do hold a value. There’s always something new to learn…
Learn more about array_filter in the PHP.net manual