Check arrays for recursion

前端 未结 5 1069
误落风尘
误落风尘 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:03

    The following function is simpler[opinion] than the code in the accepted answer, and seems to work for any use case that I have been able to contrive. It also seems to be surprisingly fast, typically taking microseconds, though I have not done extensive benchmarking. If there is a problem with it, I would be grateful if somebody could point it out?

    // returns TRUE iff the passed object or array contains
    // a self-referencing object or array
    function is_r($obj, &$visited=array())
      {
      $visited[] = $obj;
      foreach ($obj as $el)
        {
        if (is_object($el) || is_array($el))
          {
          if (in_array($el, $visited, TRUE))
            return TRUE;
          if (is_r($el, $visited))
            return TRUE;
          }
        }
      return FALSE;
      }
    

提交回复
热议问题