Home > Backend Development > PHP Problem > 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
Release: 2023-03-09 11:18:02
Original
2012 people have browsed it

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 )
Copy after login
  • $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));
?>
Copy after login
输出结果: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)
Copy after login

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>";
 ?>
Copy after login
输出结果:
array(0) { } array is empty: bool(true)
object(C)#1 (0) { }
Countable is empty: bool(false)
Copy after login

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!

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