3

How to remove empty data from an array?

var_dump($array);

array(1)  
  {    [0]=>     
    array(4) 
    { 
     [0]=> string(0) "" 
     [1]=> string(3) "car" 
     [2]=> string(4) "bike"
     [3]=> string(1) " " 
    }   
  }

I add array_filter($array); nothing removed. so how to remove "" and " " or if have more empty space in the array?

5 Answers 5

12
$array = array_filter($array, 'trim');

[edit]

This will indeed fail on some values like '0', and non-string values.

A more thorough function is:

$array = array_filter($array, function($a){
    return is_string($a) && trim($a) !== "";
});

This will only return strings that fit your request.

Sign up to request clarification or add additional context in comments.

2 Comments

What do you mean? Yes it does.
@codaddict Yes, you're right, although you should always consider what your input will be and how far you want to go. Anyway, I posted an alternative that is just a little more code.
3

I think you're trying to achieve this behavior:

<?php
$foo = array(
    array(
        'foo',
        ' ',
        'bar',
        0,
        false,
    ),
);

function array_clean(array $haystack)
{
    foreach ($haystack as $key => $value) {
        if (is_array($value)) {
            $haystack[$key] = array_clean($value);
        } elseif (is_string($value)) {
            $value = trim($value);
        }

        if (!$value) {
            unset($haystack[$key]);
        }
    }

    return $haystack;
}

print_r(array_clean($foo));

The script will output:

Array
(
    [0] => Array
        (
            [0] => foo
            [2] => bar
        )

)

Right?

1 Comment

That's quite elaborate. Generic enough to allow nested arrays, but it will still leave the number 1, while removing string '0'.
1

Create a callback function which trims whitespace from the input element and return TRUE if the trimmed element isn't empty:

$array = array_filter($array, function($x) { 
  $x = trim($x);
  return !empty($x);
});

// Example:
$array = array(1,2,"",3," ",5);

print_r($array);
Array
(
    [0] => 1
    [1] => 2
    [3] => 3
    [5] => 5
)

Comments

1

According to the doc of array_filter() :

$entry = array(
             0 => 'foo',
             1 => false,
             2 => -1,
             3 => null,
             4 => ''
          );

print_r( array_filter( $entry ) ); //Array ( [0] => foo [2] => -1 )

Comments

0
// removes all NULL, FALSE and Empty Strings but leaves 0 (zero) values
$result = array_filter( $array, 'strlen' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.