In PHP, array is a very commonly used data structure. We often need to use arrays in many programming scenarios. So when processing an array, you often need to consider whether the array is empty and how to get the length of the array.
PHP provides many functions to process arrays, such as the function empty() to determine whether the array is empty, the function isset() to determine whether the array element exists, the function count() to obtain the length of the array, etc. This article will focus on how to get the length of an array that is not empty.
When we use the count() function to get the array length, if the array is empty, 0 will be returned. But in some scenarios, you need to get the length of the array that is not empty, so what should you do?
A common method is to use a loop to traverse the array and count the number of elements that are not empty. The specific implementation is as follows:
function countNotNull($arr){ if(!is_array($arr)) return 0; $count = 0; foreach($arr as $item){ if(!empty($item)){ $count++; } } return $count; } $arr = array(1, null, 3, "", 5, array()); echo countNotNull($arr); // output: 3
The above code first determines whether the array is empty and whether it is an array type to prevent errors caused by passing in illegal parameters. Then by traversing each element, count the number of elements that are not empty. Finally return this value.
Although this method is relatively simple, it is less efficient when there are many array elements. In addition, when using this function multiple times, it may cause some duplication of work.
A more efficient solution is to use the array_filter() function to filter out empty elements, and then use the count() function to get the length of the array. The specific implementation is as follows:
function countNotNull2($arr){ if(!is_array($arr)) return 0; $newArr = array_filter($arr); return count($newArr); } $arr = array(1, null, 3, "", 5, array()); echo countNotNull2($arr); // output: 3
The above code first judges the legality of the parameters, then uses the array_filter() function to filter out empty elements and returns a new array. Then use the count() function to obtain the length of the new array, which is the length of the array that is not empty.
It should be noted that using the array_filter() function filters out empty elements (such as 0, "", null, false, etc.) instead of just filtering out empty strings.
In short, in PHP, there are many ways to get the length of an array that is not empty. The above are only the common ones. Readers can choose the appropriate method according to actual needs.
The above is the detailed content of How to get the length of an array that is not empty in php. For more information, please follow other related articles on the PHP Chinese website!