In PHP, there are many ways to return the number of arrays. The following are four commonly used methods:
For example:
$array = array('apple', 'banana', 'cherry', 'date'); $count = count($array); echo $count; //输出结果为4
For example:
$array = array('apple', 'banana', 'cherry', 'date'); $size = sizeof($array); echo $size; //输出结果为4
For example:
$array = array('apple', 'banana', 'cherry', 'banana', 'apple', 'date'); $count_array = array_count_values($array); print_r($count_array); //输出结果为: //Array //( // [apple] => 2 // [banana] => 2 // [cherry] => 1 // [date] => 1 //)
However, when the array is an object, the count() function calls the object's __count() method to count the number of elements. If the object does not define this method, an error will be thrown.
The sizeof() function does not call this method, it just returns the number of attributes in the object.
For example:
class MyArray implements Countable { private $array; public function __construct() { $this->array = array('apple', 'banana', 'cherry', 'date'); } public function count() { return count($this->array) + 1; } } $my_array = new MyArray(); echo count($my_array); //输出结果为5 echo sizeof($my_array); //输出结果为1
The above is the detailed content of PHP method to return the number of arrays. For more information, please follow other related articles on the PHP Chinese website!