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)
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:
First of all, we must agree on what empty means. Do you mean to filter out:
$element === false)empty() function?To filter out empty strings only:
$filtered = array_diff($originalArray, array(""));
To only filter out strictly false values, you must use a callback function:
$filtered = array_diff($originalArray, 'myCallback');
function myCallback($var) {
return $var === false;
}
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 and false, etc, leaving only 0):
$filtered = array_filter($originalArray, 'myCallback');
function myCallback($var) {
return ($var === 0 || $var === '0');
}
Third and fourth case are (for our purposes at last) equivalent, and for that all you have to use is the default:
$filtered = array_filter($originalArray);