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.
The most popular answer on this topic is absolutely INCORRECT.
Consider the following PHP script:
Why is this? Because a string containing a single '0' character also evaluates to boolean false, so even though it's not an empty string, it will still get filtered. That would be a bug.
Passing the built-in strlen function as the filtering function will work, because it returns a non-zero integer for a non-empty string, and a zero integer for an empty string. Non-zero integers always evaluate to true when converted to boolean, while zero integers always evaluate to false when converted to boolean.
So, the absolute, definitive, correct answer is:
If you are working with a numerical array and need to re-index the array after removing empty elements, use the array_values function:
Also see: PHP reindex array?
"If no callback is supplied, all entries of input equal to FALSE will be removed." -- http://php.net/manual/en/function.array-filter.php
You can use
array_filter
to remove empty elements:If you have
(int) 0
in your array, you may use the following:EDIT: Maybe your elements are not empty per se but contain one or more spaces... You can use the following before using
array_filter