PHP: Self-referencing array

后端 未结 2 1077
广开言路
广开言路 2020-12-01 08:53

Is there a way of referencing an array key from within the array? This may make more sense in code format:

$array=array(
  \"Key1\"=>array(
    \"Value1\"         


        
相关标签:
2条回答
  • 2020-12-01 09:29

    Impossible to make it in one block, because you not initialized the variable yet. Same with class variables. To do such thing, you will need to create any variable any way, and than use its links only, but its using memory, so once again, real answer to your question is - impossible :)

    0 讨论(0)
  • 2020-12-01 09:47

    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...

    0 讨论(0)
提交回复
热议问题