Home >Backend Development >PHP Problem >How to use count() function in PHP
PHP
It is often necessary to count the number of cells in an array or the number of attributes in an object. In this case, use count()
correctly. Functions can quickly solve such troubles.
count() syntax
count ( mixed $arr , [int $mode])
$arr
: Array or Countable
Object.
$mode
: If the optional mode parameter is set to COUNT_RECURSIVE
(or 1), count()
The array will be counted recursively. Particularly useful for computing all elements of multidimensional arrays.
Return value: Returns the number of units in $arr
.
Traversal of one-dimensional array:
<?php $a[0] = 1; $a[1] = 3; $a[2] = 5; var_dump(count($a)); ?>
Traversal of two-dimensional array:
<?php $arr2 = array('apple', 'banana', array('cat', 'camel'), 'dog'); $count1 = count($arr2); // 4 $count2 = count($arr2, 1); // 6 ?>
Traversal of objects
<?php class People { private $name; private $sex; private $age; } echo count(new People()); // 1 echo "<br>"; $p1=new People(); $c2 = count((array) $p1); echo $c2;// 3 ?>
Recommended: 《2021 PHP interview questions summary ( Collection)》《php video tutorial》
The above is the detailed content of How to use count() function in PHP. For more information, please follow other related articles on the PHP Chinese website!