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
Release: 2024-12-17 05:25:25
Original
545 people have browsed it

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);
Copy after login

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 !== "";')));
Copy after login

Reindexing Array

To reindex the array after removing empty elements:

$linksArray = array_values(array_filter($linksArray));
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template