I'm trying to find a way to get a string representation of a variable in PHP for checking if I've encountered that variable before. I'm implementing a function that recursively processes an array and it would be useful to prevent infinite recursion.
Right now I'm storing a reference to each variable I've processed in a separate array and then comparing that to the current variable (using ===
to see if they are the same instance), but that requires an O(n)
lookup. If I can get a consistent string representation I can change that to an O(1)
operation.
I was hoping I could get the internal variable ID or something similar.
Here is an example of what I'm doing now (super basic):
$a = ['a' => 'value a', 'b' => 'value b'];
$b = ['test' => &$a];
$c = ['a' => &$a, 'b' => &$b];
$a['c'] = &$c;
$b['c'] = &$c;
function process_array($array, &$tracker, $depth = 0)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
// Check for recursion
foreach ($tracker as $prev) {
if ($prev === $value) {
echo str_repeat(' ', $depth * 2) . "*RECURSION*\n";
return;
}
}
// Keep track of variables we have already processed to detect recursion
$tracker[] = &$value;
echo str_repeat(' ', $depth * 2) . "Key: {$key}\n";
process_array($value, $tracker, $depth + 1);
} else {
echo str_repeat(' ', $depth * 2) . "Key: {$key}\n";
echo str_repeat(' ', $depth * 2) . "Value: {$value}\n";
}
}
}
$tracker = array();
process_array($c, $tracker);
Output:
Key: a
Key: a
Value: value a
Key: b
Value: value b
Key: c
*RECURSION*
*RECURSION*
And another example, I'm trying to achieve something similar to print_r
:
Array
(
[a] => Array
(
[a] => value a
[b] => value b
[c] => Array
(
[a] => Array
*RECURSION*
[b] => Array
(
[test] => Array
*RECURSION*
[c] => Array
*RECURSION*
)
)
)
[b] => Array
(
[test] => Array
(
[a] => value a
[b] => value b
[c] => Array
(
[a] => Array
*RECURSION*
[b] => Array
*RECURSION*
)
)
[c] => Array
(
[a] => Array
(
[a] => value a
[b] => value b
[c] => Array
*RECURSION*
)
[b] => Array
*RECURSION*
)
)
)