2

I have the following problem. There are some php lines.

In the var_dump of $testArrayA, the "def" entry with test2 is NOT there because it was added after $testArrayB was added to $testArrayA.

It seems to me that in my case, that $testArrayB is not stored by reference in $testArrayA. How can I store it per reference, what do I have to make to have "def" entry in the var_dump?

Thanks alot in advance

$testArrayA = [];
$testArrayB = [];
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = $testArrayB;
$testArrayB["def"] = "test2";

The var_dump:

array(1) {
  ["abc"]=>
    array(1) {
       ["ghi"]=>
       string(5) "test1"
      }
}

4 Answers 4

7

This is simply a matter of passing by reference:

$testArrayA = [];
$testArrayB = [];
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = &$testArrayB;
$testArrayB["def"] = "test2";

var_dump($testArrayA);

array (size=1)
'abc' => &
array (size=2)
  'ghi' => string 'test1' (length=5)
  'def' => string 'test2' (length=5)
Sign up to request clarification or add additional context in comments.

Comments

6

Use:

$testArrayA["abc"] = &$testArrayB;

Note:

Different with C's pointer, references in PHP are a means to access the same variable content by different names.

Comments

1

in the php manual

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

Comments

0
$testArrayA = null;
$testArrayB = null;
$testArrayB["ghi"] = "test1";
$testArrayA["abc"] = $testArrayB;
$testArrayB["def"] = "test2";
print_r($testArrayA);
echo ("<br>");
print_r($testArrayB);


Array ( [abc] => Array ( [ghi] => test1 ) ) 
Array ( [ghi] => test1 [def] => test2 ) 

The 'def' entry is a different reference with the 'ghi', but they all belong testArrayB.

$testArrayA["abc"] = $testArrayB;

This code only is value reference ,not address reference.

Comments

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.