In the PHP development process, arrays are a frequently used data structure; in practical applications, it is often necessary to delete empty elements in the array in order to better process and use the array and improve development efficiency.
So, how to remove empty array elements in PHP?
1. Use foreach loop traversal
We can use foreach loop to traverse the array, and then delete the array elements by judging whether they are empty. The example is as follows:
$arr = array('a', '', 'c', 'd', ''); foreach ($arr as $key => $value) { if (empty($value)) { unset($arr[$key]); } } print_r($arr);
The above code , use foreach
to loop through all elements in the $arr
array, and determine whether $value
is empty. If it is empty, use unset
Function removes the element from the array.
2. Use the array_filter function
Another common method is to use the array_filter
function. It can accept an array as a parameter and return a new array that does not contain values FALSE
, NULL
, ''
or []
element, its syntax is as follows:
$new_arr = array_filter($arr); print_r($new_arr);
3. Use array_values function
Use array_filter
function to delete empty elements, the returned array may There will be cases where the key names are discontinuous; in order to make the key names continuous, we can use the array_values
function. The function of this function is to return all the values in the array and re-establish continuous integer indexes, for example:
$new_arr = array_values(array_filter($arr)); print_r($new_arr);
In the above code, we use array_filter
to delete empty elements, and then use the array_values
function to re-establish continuous integer indexes.
4. Use the array_reduce function
If the array contains empty array elements, the array_filter
function still cannot delete these elements; at this time we can use The array_reduce
function traverses the array and uses conditional operators to delete empty elements. The example is as follows:
$arr = array('a', '', 'c', 'd', array()); $new_arr = array_reduce($arr, function($result, $item) { return is_array($item) || $item !== '' ? array_merge($result, array($item)) : $result; }, array()); print_r($new_arr);
In the above code, the array_reduce
function is used to reduce the array$arr
Traverse once and use conditional operators to delete empty elements.
5. Summary
There are many ways to remove empty array elements in PHP, such as using foreach
loop traversal, array_filter
function, array_values
function, array_reduce
function, etc.; the specific method you should choose depends on the actual situation and personal habits. No matter which method is used, you need to understand their working principles and pay attention to modifications to the original array to avoid affecting subsequent calculations and uses.
The above is the detailed content of How to remove empty elements from an array in php. For more information, please follow other related articles on the PHP Chinese website!