


Analysis of the source code of array_keys and array_unique functions in PHP, arraykeys_PHP tutorial
Analysis of array_keys and array_unique function source code in PHP, arraykeys
Performance analysis
From the perspective of running performance, take a look at the following test code:
$test=array(); for($run=0; $run<10000; $run++) $test[]=rand(0,100); $time=microtime(true); $out = array_unique($test); $time=microtime(true)-$time; echo 'Array Unique: '.$time."\n"; $time=microtime(true); $out=array_keys(array_flip($test)); $time=microtime(true)-$time; echo 'Keys Flip: '.$time."\n"; $time=microtime(true); $out=array_flip(array_flip($test)); $time=microtime(true)-$time; echo 'Flip Flip: '.$time."\n";
The running results are as follows:
As you can see from the picture above, using the array_unique function takes 0.069s; using array_flip and then using the array_keys function takes 0.00152s; using the array_flip function twice takes 0.00146s.
The test results show that using array_flip and then calling the array_keys function is faster than the array_unique function. So, what is the specific reason? Let's take a look at how these two functions are implemented at the bottom of PHP.
Source code analysis
/* {{{ proto array array_keys(array input [, mixed search_value[, bool strict]]) Return just the keys from the input array, optionally only for the specified search_value */ PHP_FUNCTION(array_keys) { //变量定义 zval *input, /* Input array */ *search_value = NULL, /* Value to search for */ **entry, /* An entry in the input array */ res, /* Result of comparison */ *new_val; /* New value */ int add_key; /* Flag to indicate whether a key should be added */ char *string_key; /* String key */ uint string_key_len; ulong num_key; /* Numeric key */ zend_bool strict = 0; /* do strict comparison */ HashPosition pos; int (*is_equal_func)(zval *, zval *, zval * TSRMLS_DC) = is_equal_function; //程序解析参数 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|zb", &input, &search_value, &strict) == FAILURE) { return; } // 如果strict是true,则设置is_equal_func为is_identical_function,即全等比较 if (strict) { is_equal_func = is_identical_function; } /* 根据search_vale初始化返回的数组大小 */ if (search_value != NULL) { array_init(return_value); } else { array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(input))); } add_key = 1; /* 遍历输入的数组参数,然后添加键值到返回的数组 */ zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(input), &pos);//重置指针 //循环遍历数组 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(input), (void **)&entry, &pos) == SUCCESS) { // 如果search_value不为空 if (search_value != NULL) { // 判断search_value与当前的值是否相同,并将比较结果保存到add_key变量 is_equal_func(&res, search_value, *entry TSRMLS_CC); add_key = zval_is_true(&res); } if (add_key) { // 创建一个zval结构体 MAKE_STD_ZVAL(new_val); // 根据键值是字符串还是整型数字将值插入到return_value中 switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(input), &string_key, &string_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(new_val, string_key, string_key_len - 1, 0); // 此函数负责将值插入到return_value中,如果键值已存在,则使用新值更新对应的值,否则直接插入 zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; case HASH_KEY_IS_LONG: Z_TYPE_P(new_val) = IS_LONG; Z_LVAL_P(new_val) = num_key; zend_hash_next_index_insert(Z_ARRVAL_P(return_value), &new_val, sizeof(zval *), NULL); break; } } // 移动到下一个 zend_hash_move_forward_ex(Z_ARRVAL_P(input), &pos); } } /* }}} */
The above is the underlying source code of array_keys function. To facilitate understanding, the author has added some Chinese comments. If you need to view the original code, you can click to view it. The function of this function is to create a temporary array, and then copy the key-value pairs to the new array. If duplicate key values appear during the copying process, replace them with new values. The main step of this function is the zend_hash_next_index_insert function called on lines 57 and 63. This function inserts elements into the array. If a duplicate value appears, the new value is used to update the value pointed to by the original key value. Otherwise, it is inserted directly. The time complexity is O(n).
/* {{{ proto array array_flip(array input) Return array with key <-> value flipped */ PHP_FUNCTION(array_flip) { // 定义变量 zval *array, **entry, *data; char *string_key; uint str_key_len; ulong num_key; HashPosition pos; // 解析数组参数 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &array) == FAILURE) { return; } // 初始化返回数组 array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); // 重置指针 zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(array), &pos); // 遍历每个元素,并执行键<->值交换操作 while (zend_hash_get_current_data_ex(Z_ARRVAL_P(array), (void **)&entry, &pos) == SUCCESS) { // 初始化一个结构体 MAKE_STD_ZVAL(data); // 将原数组的值赋值为新数组的键 switch (zend_hash_get_current_key_ex(Z_ARRVAL_P(array), &string_key, &str_key_len, &num_key, 1, &pos)) { case HASH_KEY_IS_STRING: ZVAL_STRINGL(data, string_key, str_key_len - 1, 0); break; case HASH_KEY_IS_LONG: Z_TYPE_P(data) = IS_LONG; Z_LVAL_P(data) = num_key; break; } // 将原数组的键赋值为新数组的值,如果有重复的,则使用新值覆盖旧值 if (Z_TYPE_PP(entry) == IS_LONG) { zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else if (Z_TYPE_PP(entry) == IS_STRING) { zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { zval_ptr_dtor(&data); /* will free also zval structure */ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only flip STRING and INTEGER values!"); } // 下一个 zend_hash_move_forward_ex(Z_ARRVAL_P(array), &pos); } } /* }}} */
The above is the source code of array_flip function. Click the link to view the original code. The main thing this function does is to create a new array and traverse the original array. At line 26, the values of the original array are assigned to the keys of the new array, and then at line 37, the keys of the original array are assigned to the values of the new array. If there are duplicates, the new values are used to overwrite the old values. The time complexity of the entire function is also O(n). Therefore, the time complexity of using array_keys after using array_flip is O(n).
Next, let’s take a look at the source code of the array_unique function. Click the link to view the original code.
/* {{{ proto array array_unique(array input [, int sort_flags]) Removes duplicate values from array */ PHP_FUNCTION(array_unique) { // 定义变量 zval *array, *tmp; Bucket *p; struct bucketindex { Bucket *b; unsigned int i; }; struct bucketindex *arTmp, *cmpdata, *lastkept; unsigned int i; long sort_type = PHP_SORT_STRING; // 解析参数 if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|l", &array, &sort_type) == FAILURE) { return; } // 设置比较函数 php_set_compare_func(sort_type TSRMLS_CC); // 初始化返回数组 array_init_size(return_value, zend_hash_num_elements(Z_ARRVAL_P(array))); // 将值拷贝到新数组 zend_hash_copy(Z_ARRVAL_P(return_value), Z_ARRVAL_P(array), (copy_ctor_func_t) zval_add_ref, (void *)&tmp, sizeof(zval*)); if (Z_ARRVAL_P(array)->nNumOfElements <= 1) { /* 什么都不做 */ return; } /* 根据target_hash buckets的指针创建数组并排序 */ arTmp = (struct bucketindex *) pemalloc((Z_ARRVAL_P(array)->nNumOfElements + 1) * sizeof(struct bucketindex), Z_ARRVAL_P(array)->persistent); if (!arTmp) { zval_dtor(return_value); RETURN_FALSE; } for (i = 0, p = Z_ARRVAL_P(array)->pListHead; p; i++, p = p->pListNext) { arTmp[i].b = p; arTmp[i].i = i; } arTmp[i].b = NULL; // 排序 zend_qsort((void *) arTmp, i, sizeof(struct bucketindex), php_array_data_compare TSRMLS_CC); /* 遍历排序好的数组,然后删除重复的元素 */ lastkept = arTmp; for (cmpdata = arTmp + 1; cmpdata->b; cmpdata++) { if (php_array_data_compare(lastkept, cmpdata TSRMLS_CC)) { lastkept = cmpdata; } else { if (lastkept->i > cmpdata->i) { p = lastkept->b; lastkept = cmpdata; } else { p = cmpdata->b; } if (p->nKeyLength == 0) { zend_hash_index_del(Z_ARRVAL_P(return_value), p->h); } else { if (Z_ARRVAL_P(return_value) == &EG(symbol_table)) { zend_delete_global_variable(p->arKey, p->nKeyLength - 1 TSRMLS_CC); } else { zend_hash_quick_del(Z_ARRVAL_P(return_value), p->arKey, p->nKeyLength, p->h); } } } } pefree(arTmp, Z_ARRVAL_P(array)->persistent); } /* }}} */
As you can see, this function initializes a new array, then copies the values to the new array, and then calls the sorting function on line 45 to sort the array. The sorting algorithm is the block tree sorting algorithm of the zend engine. Then iterate through the sorted array and delete duplicate elements. The most expensive part of the entire function is calling the sorting function, and the time complexity of quick sort is O(nlogn). Therefore, the time complexity of this function is O(nlogn).
Conclusion
Because the bottom layer of array_unique calls the quick sort algorithm, which increases the time cost of function running, causing the entire function to run slower. That's why array_keys is faster than array_unique function.
Articles you may be interested in:
- Judge whether the same value exists in the array under php array_unique
- php json_encode after array_unique needs attention
- php array array_unique() of function sequence - remove duplicate element values in the array
- array_keys() of php array function sequence - get the array key name
- PHP get the position of an element in the array and array_keys function Application

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


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

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.