简体   繁体   English

PHP的in_array是否真的遍历整个数组?

[英]Does PHP's in_array really go through the whole array?

I stumbled over a few articles (eg this one ) and infos that suggest PHP's in_array() goes through the whole array. 我偶然发现了几篇文章(例如, 这篇文章)和有关PHP的in_array()遍历整个数组的信息。

Now there is a possible duplicate of this question here: How does PHP's in_array function work? 现在,此问题可能重复出现: PHP的in_array函数如何工作? but the OP was obviously satisfied with the copy/paste of the C language function definition and no further description... 但是OP显然对C语言函数定义的复制/粘贴感到满意,并且没有进一步的描述...

My question however is: 但是我的问题是:

Does PHP's in_array() really go through the whole array? PHP的in_array()是否真的遍历整个数组?

I tried to look further and go after the ZEND_HASH_FOREACH_KEY_VAL , but then it got a bit confusing: 我尝试进一步看一下并ZEND_HASH_FOREACH_KEY_VAL ,但随后有点令人困惑:

Only thing I am sure of is that since the ??iteration?? 我唯一能确定的是,从“迭代”开始 happens on the "C-level" it should be faster than "manual" foreach ... 发生在“ C级”上,它应该比“手动” foreach更快...

Does PHP's in_array really go through the whole array? PHP的in_array是否真的遍历整个数组?

TLDR; TLDR; No it doesn't. 不,不是。

The way I read the C implementation: 我阅读C实现的方式:

  1. ZEND_HASH_FOREACH_KEY_VAL or rather ZEND_HASH_FOREACH iterates over the array data bucket with a pointer to the current element. ZEND_HASH_FOREACH_KEY_VAL或更确切地说ZEND_HASH_FOREACH使用指向当前元素的指针遍历数组数据存储桶。
  2. The element pointer is assigned to the variable entry in void php_search_array for each iteration. 对于每次迭代,将元素指针分配给void php_search_array中的变量条目
  3. When a match is found, The PHP list item itself or PHP bool is returned by the engine depending on the behavior argument given to the function. 找到匹配项时,引擎将根据给函数的行为参数返回PHP列表项本身或PHP bool。

To answer your question: 要回答您的问题:

php_search_array either invokes Zend RETURN_TRUE (impl: https://github.com/php/php-src/blob/master/Zend/zend_API.h ) or sets RET_VAL and performs a C return; php_search_array要么调用Zend RETURN_TRUE (即: https : //github.com/php/php-src/blob/master/Zend/zend_API.h ),要么设置RET_VAL并执行C返回; afterwards. 然后。 It both cases, C execution breaks out of the iteration of the array if a match is found. 在这两种情况下,如果找到匹配项,C执行都会中断数组的迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM