tags:

views:

45

answers:

3

I have an array thats generated dynamically and it has some empty elements. How do I get rid of empty elements from an array?

array
0 => string '' (length=0)
1 => string 'x%6wm' (length=5)
2 => string 'x%6wmvf' (length=7) 3 => string 'x%645' (length=5) 4 => string '' (length=0)

And I want it to become like

array
0 => string 'x%6wm' (length=5)
1 => string 'x%6wmvf' (length=7)
2 => string 'x%645' (length=5)
Thanks

A: 

You can loop throuh it and check each element of the array if empty or not and if it's empty you can delete that element.

SzamDev
Inefficient. Always use PHP built in functions when available -- theyre usually just wrappers to C functions, and as such, are super quick. Looping through manually would take forever.
Travis Leleu
@Travis Leleu: Good point :)
SzamDev
+2  A: 

You can combine the functions array_filter() and array_values() to accomplish your goal.

$cleanArray = array_values(array_filter($array));

Piro
Is the array_values call necessary if you don't have any associative keys?
The Real Diel
If you want to keep your array keys intact you should leave out `array_values`. However, if you want to have your array keys reset and without gaps you need to add this function.
Piro
A: 
darren102