Home >Backend Development >PHP Problem >php remove empty array
In PHP, we often need to process arrays, but sometimes we need to perform some operations on the array, such as removing empty elements from the array. Empty elements may affect our other operations on the array, so they need to be removed. This article will show you how to remove empty elements from an array using PHP.
PHP provides an array_filter() function, which can be used to filter elements in an array. We can write a callback function and use this function to filter the array and remove empty elements.
The following is a sample code:
<?php $fruits = array("apple", "banana", "", "orange", "", "peach"); $new_fruits = array_filter($fruits); print_r($new_fruits); ?>
Output:
Array ( [0] => apple [1] => banana [3] => orange [5] => peach )
As you can see, the empty elements have been successfully removed from the new array.
Another way to process an array is to use a foreach loop. We can traverse the array and check whether each element is empty. Removes an empty element when it is encountered.
The following is a sample code:
<?php $fruits = array("apple", "banana", "", "orange", "", "peach"); foreach ($fruits as $key => $value) { if($value == ""){ unset($fruits[$key]); } } print_r($fruits); ?>
Output:
Array ( [0] => apple [1] => banana [3] => orange [5] => peach )
You can also see that the empty elements have been successfully removed from the array.
We can also use the array_diff() function provided by PHP, which can be used to compare the difference between two arrays and return the difference result. If we want to remove empty elements from an array, we can remove the empty elements by comparing the difference with another array that has only empty elements.
The following is a sample code:
<?php $fruits = array("apple", "banana", "", "orange", "", "peach"); $empty_elem = array(""); $new_fruits = array_diff($fruits, $empty_elem); print_r($new_fruits); ?>
Output:
Array ( [0] => apple [1] => banana [3] => orange [5] => peach )
As you can see, the empty elements have been successfully removed from the new array.
Summary
This article introduces three methods of using PHP to remove empty elements in an array. Use the array_filter() function to filter by using a callback function, use a foreach loop to check and remove empty elements one by one, and use the array_diff() function to remove the elements you want to remove by comparing them with another array. You can choose any of these methods to remove empty elements from the array according to actual needs.
The above is the detailed content of php remove empty array. For more information, please follow other related articles on the PHP Chinese website!