Home >Backend Development >PHP Tutorial >How Can I Efficiently Remove Empty Elements from a PHP Array?

How Can I Efficiently Remove Empty Elements from a PHP Array?

DDD
DDDOriginal
2024-12-17 05:25:25640browse

How Can I Efficiently Remove Empty Elements from a PHP Array?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn