Check arrays for recursion

前端 未结 5 1072
误落风尘
误落风尘 2021-02-05 22:29

What is the best way to check if an array is recursive in PHP ?

Given the following code:



        
5条回答
  •  旧巷少年郎
    2021-02-05 23:01

    Many of the solutions you will find on SO are broken (see explanation below). The function I propose works for all arrays and is much more efficient than print_r:

    function is_cyclic(&$array) {
        $isRecursive = false;
        set_error_handler(function ($errno, $errstr) use (&$isRecursive) {
            $isRecursive = $errno === E_WARNING && mb_stripos($errstr, 'recursion');
        });
        try {
            count($array, COUNT_RECURSIVE);    
        } finally {
            restore_error_handler();
        }
        return $isRecursive;
    }
    

    The count function takes a second parameter $mode that can be set to the constant COUNT_RECURSIVE to count recursively (see docs). If a recursive array gets passed to count, it will emit a warning that we can trap and check. I have written more about this solution on my blog. Tests and benchmarks are on github.

    Why are most solutions broken?

    Any implementation that adds markers to arrays and then later checks for the presence of these markers does not work for all inputs. Specifically, they fail to detect recursion in some cases where the arrays have previously been assigned by value (e.g. returned by a function). This is due to the way PHP handles value assignments of arrays, as described in chapter 4 of the PHP Language Specification. I have written more extensively about this on my blog.

提交回复
热议问题