Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:
foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
But it doesn't work, $linksArray
still has empty elements. I have also tried doing it with the empty()
function but the outcome is the same.
I had to do this in order to keep an array value of (string) 0
In short:
This is my suggested code:
Explanation:
I thinks use
array_filter
is good, but not enough, because values be likespace
and\n
,... keep in the array and this is usually bad.So I suggest you use mixture
array_filter
andarray_map
.array_map
is for trimming,array_filter
is for remove empty values,strlen
is for keep0
value, andarray_values
is for re indexing if you needed.Samples:
Results:
Online Test:
http://phpio.net/s/5yg0
The most voted answer is wrong or at least not completely true as the OP is talking about blank strings only. Here's a thorough explanation:
What does empty mean?
First of all, we must agree on what empty means. Do you mean to filter out:
$element === false
)empty()
function?How do you filter out the values
To filter out empty strings only:
To only filter out strictly false values, you must use a callback function:
The callback is also useful for any combination in which you want to filter out the "falsey" values, except some. (For example, filter every
null
andfalse
, etc, leaving only0
):Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:
Remove empty array elements
¡it works!