Skip to content

Instantly share code, notes, and snippets.

@markdrake
Created July 10, 2014 05:06
Show Gist options
  • Save markdrake/0f9481fa2807f88a4177 to your computer and use it in GitHub Desktop.
Save markdrake/0f9481fa2807f88a4177 to your computer and use it in GitHub Desktop.
Code to remove null elements from an array in php with array_filter
<?php
$array = [null, 1, null, 2, 3, 5];
var_dump(array_filter($array));
// This also works for numeric index values, notice how the null value indexes are stripped
$array = [
0 => null,
1 => 22,
2 => null,
3 => 1,
4 => 33,
5 => 57
];
var_dump(array_filter($array)); // Should print [1 => 22, 3 => 1, 4 => 33, 5 =>57]
// For associative arrays the null keys are unset //
$array = [
'lol' => null,
'more' => 22,
'nope' => null,
'wow' => 1,
];
print_r(array_filter($array)); // Should print [[more] => 22 [wow] => 1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment