Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if variable contains circular references

How do you test a variable for circular references?

I am using PHP's var_export() function with the return string argument set to true.

I found that Warning: var_export does not handle circular references and was wondering if anyone knew of a way to test if a variable contains a circular reference so that I may use it before trying to use var_export on it.

I know that var_export outputs PHP eval-able text that can be used to recreate the array and even though I am not using it for that I still want to use this function when it is available because the output format meets my needs. var_dump is not an option because it doesn't accept an argument to return a string instead. I am aware that I could buffer the output of var_dump which handles circular references gracefully and save the buffer contents to a variable but I really just want to know if someone knows of a way to test for such references in a variable.

If you want to create a quick circular reference do this:

$r = array();
$r[] = &$r;
var_export($r, true);
like image 611
km6zla Avatar asked Jun 19 '13 01:06

km6zla


1 Answers

Hacky but returns true based on the circular example you gave:

<?php
// create the circular reference
$r = array();
$r[] = &$r;

function isRecursive($array){
  $dump = print_r($array, true);
  if(strpos($dump, '*RECURSION*') !== false)
      return true;
  else
      return false;
}

echo isRecursive($r); // returns 1

Interested to see what else people come up with :)

like image 194
BIOS Avatar answered Oct 01 '22 17:10

BIOS