Home > Article > Backend Development > How to use count function in php
Use the count() function to calculate the number of elements: Array: count([1, 2, 3]) returns the number of array elements. String: count("Hello World!") returns the number of characters. Object: An object that implements the Countable interface, such as SplObjectStorage, can use count() to count the number of elements. Iterable objects: You can use iterable objects such as SplObjectStorage to count the number of elements. Non-array, string, or iterable object variable: count() returns null.
How to use count() function in PHP
The count() function is used to count arrays in PHP , the number of elements of a string or object.
Syntax
count(variable)
where variable
can be:
Countable
interface) SplObjectStorage
)Usage
For arrays, the count() function returns the number of elements in the array:
<code class="php">$arr = [1, 2, 3, 4, 5]; $count = count($arr); // $count 为 5</code>
For strings , The count() function returns the number of characters in the string:
<code class="php">$str = "Hello World!"; $count = count($str); // $count 为 12</code>
For objects, the count() function only applies to objects that implement the Countable
interface. The Countable
interface defines a count()
method, which returns the number of elements in the object.
For example, for a SplObjectStorage
object, you can use the count() function to calculate the number of objects stored:
<code class="php">$storage = new SplObjectStorage(); $storage->attach(new stdClass()); $count = count($storage); // $count 为 1</code>
Note:
variable
is not an array, string, or object implementing the Countable
interface, the count() function will return null
. 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!