PHP: Self-referencing array

The answer to this, as it turns out, is Yes. However it is not a tidy syntax as it uses a sort of sub-statement, and leaves the current scope littered with an extra reference variable.

Consider the following code:

<?php

  $array = array(

    // Creates Key1 and assigns the value to it
    // A copy of the value is also placed in $ref
    // At this stage, it's not a reference
    "Key1"=>($ref = array(
      "Value1",
      "Value2"
    )),

    // Now Key2 is a reference to $ref, but not to Key1
    "Key2"=>&$ref,

    // Now everything is referenced together
    "Key1"=>&$ref

  );

I was surprised that this worked with no errors, but it does – here’s the proof. Of course, you wouldn’t do this, but you can…

Leave a Comment