在PHP编程中,在遍历数组的时候经常需要先计算数组的长度作为循环结束的判断条件,而在PHP里面对数组的操作是很频繁的,因此count也算是一个常用函数,下面研究一下count函数的具体实现。
我在github上有对PHP源码更详细的注解。感兴趣的可以围观一下,给个star。PHP5.4源码注解。可以通过commit记录查看已添加的注解。
count
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
count函数计算数组或者对象里面的所有元素个数。
对于对象来说,如果你安装了SPL扩展,可以通过实现Countable接口来调用count函数。Countable接口有且仅有一个方法Countable::count(),该方法的返回count()函数的返回值。
参数说明
mode
如果参数mode设为COUNT_RECURSIVE(或1),count()会递归地计算该数组。在计算多维数组的时候特别有用。
如果第一个参数不是数组或者实现Countable接口的对象,count函数将返回1。
注意:count函数可以检测递归避免无限循环,但会在遇到无限递归或得到比期望值大的时候返回E_WARNING提示。
运行示例
普通应用
$arr1 = array(1, 2, 3, 4, 5); $val1 = count($arr1); // 5
多维数组
$arr2 = array('apple', 'banana', array('cat', 'camel'), 'dog'); $val2_1 = count($arr2); // 4 $val2_2 = count($arr2, 1); // 6
数字和字符串
$str = "hello world"; $int_val = 1; $val3 = count($str); // 1 $val4 = count($int_val); // 1
普通对象
class User { private $name; private $address; } $user = new User(); $val5 = count($user); // 1 $val6 = count((array) $user); // 2
array-like对象
class User extends ArrayObject { private $name; public function __construct() { $this->name = 'hhq'; } public function getName() { return $this->name; } public function count() { return 2; } } $user2 = new User(); $val7 = count($user2); // 2
实现Countable接口对象
class User implements Countable { public function count() { return 3; } } $user3 = new User(); $val8 = count($user3); // 3
运行步骤
进入switch语句检测参数类型
如果是NULL,直接返回0
如果是数组,调用php_count_recursive函数机选数组元素个数
如果是对象,先检查是否为数组对象(array-like object),如果是,则计算数组对象的数量
否则,如果对象实现了Countable接口,则调用Countable的count方法
最后,其他类型比如整型数组或字符串,都返回1。
源码解读
如果是普通数组,count函数会调用php_count_recursive函数实现其功能的运行步骤如下:
如果当前hash Bucket被递归访问的次数大于1,说明重复递归,染回E_WARNING错误
否则计算当前数组层数的数组元素个数
如果有递归参数选项,则继续递归访问
如果参数是对象类型,实现时会先判断handler是否被定义。而handler是PHP内核中对象的结构体,其中包含有count_elements字段,实际上是一个函数。如果某个对象表现得想数组一样,即通常说的array-like object,那么就会执行count_elements函数。具体实现是类继承PHP的ArrayObject,并在类里面实现count函数,具体调用的就是count函数,如果类没有实现count函数,则count返回0,否则返回对象的count函数的返回值。
如果是其他的数据类型
1、字符串
2、数字
3、对象分支中两个if判断都为false的情况,即没有继承ArrayObject且没有实现Countable接口。
这些类型通通返回1。
需要注意的是,如果需要计算的是对象的属性数量,可以先将对象转换成数组,然后调用count函数。如:
$count_value = count((array) $user);
小结
阅读count函数的源码过程中,在其中一步卡住了,就是if (Z_OBJ_HT_P(array)->count_elements)这一步,因为始终无法写出进入这个分支的demo,在网上搜索了很多资料也未果,因此请教了TIPI的reeze,最终得到了想要的答案。不懂就要问,哈哈。

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.