Home  >  Article  >  Backend Development  >  How to use sizeof to get the number of array cells in PHP

How to use sizeof to get the number of array cells in PHP

autoload
autoloadOriginal
2021-04-15 10:35:031979browse

How to use sizeof to get the number of array cells in PHP

In order to obtain the number of array units or the number of attributes of an object, PHP provides the count() function, and count The alias of () is called sizeof(), and there is no difference between the two. First, let’s introduce the syntax of the count() function.

Syntax:

count ( mixed $array  , int $mode )
  • $array: array or Countable object.

  • $mode: (optional) The $mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array count.

  • Return value: Number of units. If the argument is neither an array nor an object implementing the Countable interface, 1 will be returned. If $array is null then 0 is returned.

Usage example:

1. Get the number of array cells:

<?php
    $a[0] = 1;
    $a[1] = 3;
    $a[2] = 5;
    var_dump(count($a));
    
    var_dump(count(null));
    var_dump(count(false));
?>
输出结果:int(3)
Warning: count(): Parameter must be an array or an object that ..//PHP 7.2 起int(0)
Warning: count(): Parameter must be an array or an object that ...// PHP 7.2 起int(1)

2. Object Number of attributes

<?php
class C implements Countable {
     public function count() {
         return 0;
     }
 }

 $a = [];
 var_dump($a);
 echo &#39;array is empty: &#39;; var_dump(empty($a));
echo"<br>";
 $c = new C;
 var_dump($c);
 echo"<br>";
 echo &#39;Countable is empty: &#39; ; var_dump(empty($c));
 echo"<br>";
 ?>
输出结果:
array(0) { } array is empty: bool(true)
object(C)#1 (0) { }
Countable is empty: bool(false)

Recommended: 2021 PHP interview questions summary (collection)》《php video tutorial

The above is the detailed content of How to use sizeof to get the number of array cells 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