How to trim a PHP array and remove all empty indexes
Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
[5] =>
[6] =>
[7] => 4
[8] => 6
[9] =>
)
Output should be like
Array
(
[0] => 4
[1] => 6
)
You are looking for the array_filter function ;-)
For instance, this portion of code :
$arr = array(null, 0, null, 0, '', null, '', 4, 6, '', );
$arr_filtered = array_filter($arr);
var_dump($arr_filtered);
Will give you the following output :
array
7 => int 4
8 => int 6
Note that all "falsy" values have been removed.
And if you want to be more specific, you can specify your own filtering function. For instance, to remove only nulls from the array, I could use this :
function my_filter($item) {
if ($item === null) {
return false;
}
return true;
}
$arr = array(null, 0, null, 0, '', null, '', 4, 6, '', );
$arr_filtered = array_filter($arr, 'my_filter');
var_dump($arr_filtered);
And I'd get :
array
1 => int 0
3 => int 0
4 => string '' (length=0)
6 => string '' (length=0)
7 => int 4
8 => int 6
9 => string '' (length=0)
Here another way:
<?php
$array = array(
0 => 0,
1 => ,
2 => '',
3 => 4,
4 => 6,
5 => null
);
foreach( $array as $a )
{
if( !empty($a) AND $a != NULL AND $a != 0 ) // NULL, 0
{
$new_array[] = $a;
}
}
print_r( $new_array );
?>
Output will be:
Array
(
[0] => 4
[1] => 6
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With