Home  >  Article  >  Backend Development  >  How to remove empty array in php

How to remove empty array in php

PHPz
PHPzOriginal
2023-04-25 09:03:021175browse

When programming in PHP, operating arrays is an essential task. However, when we use arrays, we often encounter empty arrays.

Empty cells in an array can cause confusion when we perform other operations, especially when calculating sums or averages.

In this article, we will introduce some methods to remove empty arrays.

Method 1: Use foreach loop and unset function

Use foreach loop to traverse the array, and use unset function to delete empty elements. The function of unset function is to destroy the specified variable.

Here is an example:

<?php
$array = array(1, null, 2, "", 3);
 
foreach ($array as $key => $value) {
    if (empty($value)) {
        unset($array[$key]);
    }
}
 
print_r($array);
?>

In this example, we use a foreach loop to traverse the array and check if each element is empty. If it is empty, use the unset function to delete the element. Finally, we will return the modified array.

Method 2: Use the array_filter function

The array_filter function is a built-in function in PHP, which can help us filter array elements. Use this function to easily remove empty arrays.

Here is an example:

<?php
$array = array(1, null, 2, "", 3);
 
$new_array = array_filter($array);
 
print_r($new_array);
?>

In this example, we use the array_filter function to filter out non-empty elements and create a new array. Finally, we will return the modified array.

Method 3: Use array_values ​​function

If we want to reset the keys of the array (i.e. delete empty cells and renumber the index), we can use the array_values ​​function.

Here is an example:

<?php
$array = array(1, null, 2, "", 3);
 
$new_array = array_values(array_filter($array));
 
print_r($new_array);
?>

In this example, we use array_filter to filter empty elements and use array_values ​​function to renumber the index. Finally, we will return the modified array.

Summary

In this article, we learned several ways to remove empty elements from an array. Whether you use a foreach loop and the unset function, the array_filter function, or the array_values ​​function, these techniques can help you solve the problem easily. Make our PHP programming more efficient and accurate.

The above is the detailed content of How to remove empty array in php. 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