The PHP array_filter()
function can be used to remove all empty/falsy values from an array when the second argument to the function is not supplied. For example:
$arr = [null, 'foo', false, 0, 0.0, '', '0', [], 'bar']; $filteredArr = array_filter($arr); echo print_r($filteredArr, true); // [1 => 'foo', 8 => 'bar']
As you can see from the result, array keys are preserved (which results in gaps in an indexed array). If you wish to reindex the array, then you can use the array_values()
function on the resulting array like so:
$arr = [null, 'foo', false, 0, 0.0, '', '0', [], 'bar']; $filteredArr = array_filter($arr); $reindexArr = array_values($filteredArr); echo print_r($reindexArr, true); // [0 => 'foo', 1 => 'bar']
Alternatively, you may also use the splat operator (...
) to unpack the array into a new array like so:
$arr = [null, 'foo', false, 0, 0.0, '', '0', [], 'bar']; $filteredArr = array_filter($arr); $reindexArr = [...$filteredArr]; echo print_r($reindexArr, true); // [0 => 'foo', 1 => 'bar']
Please note that using the splat operator (...
) might not be performant with large arrays.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.