Home >Backend Development >PHP Tutorial >How to Effectively Remove Empty Elements from a PHP Array?

How to Effectively Remove Empty Elements from a PHP Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-29 01:11:11611browse

How to Effectively Remove Empty Elements from a PHP Array?

How to Remove Empty Array Elements

Your code to remove empty elements from the $linksArray array is not working as intended. This is because unset($link) only removes the reference to the variable $link, not the element itself from the array.

The empty() function also won't work because it checks if a variable is empty, not an array element.

To remove empty elements from an array, you can use the array_filter() function. array_filter() takes an array and a callback function as arguments. The callback function is applied to each element of the array, and the element is removed from the array if the callback function returns false.

In your case, you can use the following code to remove empty elements from $linksArray:

$linksArray = array_filter($linksArray);

However, if you need to preserve elements that are exact string '0', you will need a custom callback:

// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));

// PHP 5.3 and later
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 !== "";')));

Note: If you need to reindex the array after removing the empty elements, use:

$linksArray = array_values(array_filter($linksArray));

The above is the detailed content of How to Effectively 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