Home  >  Article  >  Backend Development  >  How to use count() function in PHP

How to use count() function in PHP

autoload
autoloadOriginal
2021-04-13 17:59:362647browse

How to use count() function in PHP

PHPIt 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(&#39;apple&#39;, &#39;banana&#39;, array(&#39;cat&#39;, &#39;camel&#39;), &#39;dog&#39;);
    $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!

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