0

I have a simple way to detect references in an array (For debugging purposes)

First I clone the array with array_values and then I alter the clone and look for changes in the original. If it's changed that element is a reference.

Short example:

<?php

$a = [
    'a' => 'b',
    2 => 3,
];

$b = ['wow'];

$a['ref'] = &$b;

function getrefs($array) {
    $marker = uniqid();
    $copy = array_values($array);
    $i = 0;
    $return = [];
    foreach ($array as $key => &$val) {
        $stash = $val;
        $copy[$i] = $marker;
        if ($val === $marker) {
            $val = $stash;
            $return[] = $key;
        }
        $i++;
    }
    return $return;
}

var_dump($a);
var_dump(getrefs($a));

The problem is that when I try to use this on $GLOBALS it's not working, and I can't figure out why. Everything in $GLOBALS should be a reference by all rights.

Is $GLOBALS just so strange that it's the only array where array_values won't correctly copy references?

2
  • You didn't show your attempt with $GLOBALS. Did you try $GLOBALS['GLOBALS']? Commented Mar 29, 2017 at 18:03
  • No but I just did and it has the same result Commented Mar 29, 2017 at 18:10

1 Answer 1

1

It's a possibility that you're not accounting for recursion. The built-in PHP function:

var_dump($GLOBALS);

Will have the following output

array(7) {
   ["_GET"]=>
      array(0) {
   }
   ["_POST"]=>
      array(0) {
   }
   ["_COOKIE"]=>
      array(1) {
      ["PHPSESSID"]=>
      string(26) "od602et6qcfj6pa3pkjtl8go57"
   }
   ["_FILES"]=>
      array(0) {
   }
   ["GLOBALS"]=>
      *RECURSION*
   ["_SESSION"]=>
      &array(0) {
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nope that's not it. $GLOBALS for some reason is referenced every time it's assigned except when passed through array_values (IE: $a = $GLOBALS;$a['test'] = 1234; will result in $GLOBALS['test'] === 1234, but with array_values it looks like every last reference is broken somehow)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.