0

Im looking for a way to remove empty elements from an array. Im aware of array_filter() which removes all empty values.

The thing is that i consider a string containing nothing but spaces, tabs and newlines also to be empty.

So what is best used in this case?

3
  • 1
    array_filter($array, function ($v) { return (bool)trim($v); }); Commented Mar 16, 2014 at 8:18
  • perfect hindmost, thank you. Commented Mar 16, 2014 at 8:19
  • @Kristian Rafteseth You could choose this answer as "accepted" if you want to express your "thank". Commented Mar 16, 2014 at 9:00

3 Answers 3

2

Use trim() in callback for array_filter:

$array = array_filter($array, function ($v) { return (bool)trim($v); });

Or shorter version (with implicit type-casting):

$array = array_filter($array, 'trim');
Sign up to request clarification or add additional context in comments.

Comments

0

php empty()

bool empty ( mixed $var )

Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

Something like should do:

foreach($array as $key => $stuff)
{
    if(empty(stuff))
    {
        unset($array[$key]);
    }
}
$array  = array_values($array );// to reinstate the numerical indexes.

Comments

0

I know this may be late to answer but it is for those who may have interest in other ways to solve this. It is my own way of doing it.

function my_array_filter($my_array)
{
    $final_array = array();
    foreach ( $my_array as $my_arr ) 
    {
        //check if array element is not empty
        if (!empty($my_arr)) $final_array[] = $my_arr;
    }
    //remove duplicate elements
    return array_unique( $final_array );
}

Hope someone finds this useful.

1 Comment

That is an awesome code you got there sir and I must say it really helped me on something i have been working on

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.