php basics
Use PHP count to count the number of array elements
PHP count is very useful for counting the number of elements in an array ( PHP Array ). When we want to know how many elements there are in an array, we can get the answer by putting the array in count to count. We have prepared two simple The example of to count the number of elements in a one-dimensional array and a two-dimensional array respectively.
PHP count syntax
count ($ var, $ mode);
$var can usually be an Array, a required item, and $mode is an optional item. If you want to calculate an array of more than two dimensions, $mode can be filled with COUNT_RECURSIVE or the number 1, and the default value of $mode is 0, below It is an example of statistics.PHP count example of counting the number of elements in a one-dimensional array
<?php
$Arr=array( 'a' , 'b' , 'c' );
echo count($Arr);
?>
Output result: 3$Arr=array( 'a' , 'b' , 'c' );
echo count($Arr);
?>
PHP count counts the number of two-dimensional array elements
<?php
$Arr= array('A' => array('1', '2', '3'),
'B' => array('4', '5','6'));
echo count($Arr, COUNT_RECURSIVE);
?>
Output result: 8$Arr= array('A' => array('1', '2', '3'),
'B' => array('4', '5','6'));
echo count($Arr, COUNT_RECURSIVE);
?>
We first prepare a two-dimensional array $Arr. The first layer has two array elements, and the second layer has three elements. Then we use PHP count to count how many array elements $Arr has in total, so count Enter COUNT_RECURSIVE in the $mode, or enter 1. The value of count is just 8. If we only write count($Arr), then we can only count the result of 2, because no $mode is added, so count will only count the first level.
Supplement: The same function as the count function is the sizeof function, please refer to: PHP sizeof function .
Post a Comment
0 Comments