Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Array trim blank index values

Tags:

arrays

php

trim

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   
    )
like image 706
Mithun Sreedharan Avatar asked Dec 18 '22 02:12

Mithun Sreedharan


2 Answers

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)
like image 119
Pascal MARTIN Avatar answered Dec 29 '22 19:12

Pascal MARTIN


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
)
like image 40
ahmet2106 Avatar answered Dec 29 '22 21:12

ahmet2106