How to use count() function in PHP

autoload
Release: 2023-03-09 10:56:01
Original
2672 people have browsed it

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])
Copy after login
  • $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));
?>
Copy after login

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
?>
Copy after login

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
?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template