detecting infinite array recursion in PHP?

前端 未结 2 492
时光取名叫无心
时光取名叫无心 2021-02-07 11:36

i\'ve just reworked my recursion detection algorithm in my pet project dump_r()

https://github.com/leeoniya/dump_r.php

detecting object recursion is not too diff

2条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 12:11

    Because of PHP's call-by-value mechanism, the only solution I see here is to iterate the array by reference, and set an arbitrary value in it, which you later check if it exists to find out if you were there before:

    function iterate_array(&$arr){
    
      if(!is_array($arr)){
        print $arr;
        return;
      }
    
      // if this key is present, it means you already walked this array
      if(isset($arr['__been_here'])){
        print 'RECURSION';
        return;
      }
    
      $arr['__been_here'] = true;
    
      foreach($arr as $key => &$value){
    
        // print your values here, or do your stuff
        if($key !== '__been_here'){
          if(is_array($value)){
            iterate_array($value);
          }
    
          print $value;
        }
      }
    
      // you need to unset it when done because you're working with a reference...
      unset($arr['__been_here']);
    
    }
    

    You could wrap this function into another function that accepts values instead of references, but then you would get the RECURSION notice from the 2nd level on. I think print_r does the same too.

提交回复
热议问题