Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

reference - PHP: Self-referencing array

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",
    "Value2"
  ),
  "Key2"=>&$this['Key1']
);

What I want is for $array['Key2'] to output the same as $array['Key1']. I can add $array['Key2']=&$array['Key1']; after the array is created, but would like to keep it all in one code block if possible.

I've checked the docs on references, as well as some of the suggest similar questions here and a search for "php array reference".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...