开发者

php: array item set to another array item (sibling)

开发者 https://www.devze.com 2023-02-17 11:53 出处:网络
The item \'reference\' in the array is set to $array[\'fruit\']. But no is value returned $array = array(

The item 'reference' in the array is set to $array['fruit']. But no is value returned

$array = array(
          'fruit'=>'apple',
          'reference'=>$array['fruit']
         );

example: echo $array['reference']; //the word apple should be 开发者_运维百科displayed

How is this result achieved?


You are actually referencing the $array variable while creating it so it's normal it'll contain nothing.

This'll work but to be honest, it's kinda sketchy what you are doing.

$array = array('fruit' => 'apple');
$array['reference'] = $array['fruit'];


You will have to set it later, because $array isn't initialized yet while you're already assigning.

$array = array(
    'fruit' => 'apple'
);

$array['reference'] = &$array['fruit'];

The ampersand will create a reference to the index fruit.

Hope this helped.


Use

$array = array();
$array['fruit'] = "apple";
$array['reference'] = $array['fruit'];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号