Search code examples
phparrayszend-frameworkcontain

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


I stumbled over a few articles (e.g. this one) and infos that suggest PHP's in_array() goes through the whole array.

Now there is a possible duplicate of this question here: How does PHP's in_array function work? but the OP was obviously satisfied with the copy/paste of the C language function definition and no further description...

My question however is:

Does PHP's in_array() really go through the whole array?

I tried to look further and go after the ZEND_HASH_FOREACH_KEY_VAL, but then it got a bit confusing:

Only thing I am sure of is that since the ??iteration?? happens on the "C-level" it should be faster than "manual" foreach...


Solution

  • Does PHP's in_array really go through the whole array?

    TLDR; No it doesn't.

    The way I read the C implementation:

    1. ZEND_HASH_FOREACH_KEY_VAL or rather ZEND_HASH_FOREACH iterates over the array data bucket with a pointer to the current element.
    2. The element pointer is assigned to the variable entry in void php_search_array for each iteration.
    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.

    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; afterwards. It both cases, C execution breaks out of the iteration of the array if a match is found.