Home  >  Article  >  Backend Development  >  How to count the number of non-empty elements in an array in php

How to count the number of non-empty elements in an array in php

王林
王林Original
2020-08-13 13:32:582735browse

php method to calculate the number of non-empty elements in an array: first use the array_filter() function to use the callback function to filter the elements in the array and return the filtered array; then use the count() function to count Just the number of elements in the filtered array.

How to count the number of non-empty elements in an array in php

array_filter() function uses the callback function to filter the elements in the array and returns the filtered array.

(Related tutorial recommendation: php graphic tutorial)

This function passes each key value in the input array to the callback function. If the callback function returns true, the current key value in the input array is returned to the result array. Array key names remain unchanged.

Syntax:

array array_filter(array $array[, callable $callback[, int $flag = 0]])

Parameters:

  • ##array Required. Specifies the array to filter.

  • callback Optional. Specifies the callback function to be used.

  • #flag Optional. Determine the parameter form received by the callback: ARRAY_FILTER_USE_KEY - callback accepts the key name as the only parameter ARRAY_FILTER_USE_BOTH - callback accepts both key name and key value

(Video tutorial recommendation:

php video tutorial)

Code implementation:


<?php
$arr = array(
1=>"11",
2=>"22",
3=>"33",
4=>""
);
print_r(count(array_filter($arr)));
?>

The above is the detailed content of How to count the number of non-empty elements in an 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