Home > Article > Backend Development > 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 'array is empty: '; var_dump(empty($a)); echo"<br>"; $c = new C; var_dump($c); echo"<br>"; echo 'Countable is empty: ' ; 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!