Home > Article > Backend Development > php delete empty array elements
When developing using PHP, you often encounter situations where you need to operate on arrays. Sometimes empty elements appear in the array, and these empty elements need to be deleted to facilitate subsequent operations. Below we will introduce how to use PHP to delete empty array elements.
First, we can use the PHP built-in function unset to delete empty elements in the array. The function of unset function is to delete variables, including array elements. We can use a loop statement to traverse the array and delete array elements by determining whether the element is empty. The specific implementation code is as follows:
$array = array('a', '', 'b', 'c', '', 'd'); foreach ($array as $key => $value) { if ($value == '') { unset($array[$key]); } } print_r($array);
In the above code, we define an array $array, and use the foreach loop statement to traverse the elements in the array. For empty elements, use the unset function to delete them. The print_r function is used to output the deleted array.
Another way is to use the PHP built-in function array_filter to delete empty elements in the array. The array_filter function will traverse the elements in the array, filter and return the elements that meet the conditions. We can customize a callback function to determine whether the elements in the array are empty. The specific implementation code is as follows:
$array = array('a', '', 'b', 'c', '', 'd'); $new_array = array_filter($array, function($value) { return $value !== ''; }); print_r($new_array);
In the above code, we define an array $array. When calling the array_filter function, we define a callback function to determine whether the elements in the array are empty, and finally return a new Array $new_array. The print_r function is used to output the deleted array.
When developing with PHP, when operating arrays, we usually encounter the problem of needing to delete empty elements in the array. This article introduces two different ways to remove empty elements using the unset function and the array_filter function. The specific choice can be determined according to the actual situation, which method is more convenient and efficient.
The above is the detailed content of php delete empty array elements. For more information, please follow other related articles on the PHP Chinese website!