Removing Empty Array Elements
To efficiently remove empty elements from an array of strings, utilize array_filter(). This function conveniently handles the removal of empty values:
$linksArray = array_filter($linksArray);
Preserve Specific Non-Empty Elements
If you need to preserve specific non-empty elements, such as the exact string '0', employ a custom callback:
// PHP 7.4+ print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== '')); // PHP 5.3+ print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; })); // PHP < 5.3 print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
Reindexing Array
To reindex the array after removing empty elements:
$linksArray = array_values(array_filter($linksArray));
The above is the detailed content of How Can I Efficiently Remove Empty Elements from a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!