在php中,有很多种方法可以返回数组的数量。以下是常用的四个方法:
例如:
$array = array('apple', 'banana', 'cherry', 'date');
$count = count($array);
echo $count; //输出结果为4例如:
$array = array('apple', 'banana', 'cherry', 'date');
$size = sizeof($array);
echo $size; //输出结果为4例如:
$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
//)但是,当数组是一个对象时,count()函数会调用对象的__count()方法来统计元素的数量。如果对象没有定义这个方法,将会抛出一个错误。
立即学习“PHP免费学习笔记(深入)”;
而sizeof()函数不会调用这个方法,它只是返回对象中的属性数量。
例如:
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以上就是php返回数组数量的方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号