Jem
Jem

Reputation: 6406

PHP variable to access variable within an array

Not being used to php, I'm facing an issue with accessing arrays and its sub data.

$form['signatories']['signatory1'] = array(...);

I must create a "pointer" to the array created in the line above, I expected the following to work:

$cluster = $form['signatories']['signatory1'];

Testing I'm accessing the same "memory space" proves I'm wrong:

$cluster['signatory_name'] = array(...)
// $form['signatories']['signatory1'] has no elements
// $cluster has a sub element

Like cluster is a copy of the array I want it to point to.

How should I proceed? I tried using the "&" reference sign as mentioned in some blog, but that didn't help.

Thanks! J.

Upvotes: 3

Views: 95

Answers (2)

lonesomeday
lonesomeday

Reputation: 237865

By default, assignment in PHP is by value, not by reference, except for objects.

If you want to pass a reference to the original array, you need to create a reference explicitly:

$cluster = &$form['signatories']['signatory1'];

See assigning by reference in the PHP manual.

Upvotes: 6

Bailey Parker
Bailey Parker

Reputation: 15905

You can use =& to assign by reference:

$cluster =& $form['signatories']['signatory1'];

Effectively this is two operations. The first is &$form['signatories']['signatory1'] which gives you a reference to $form['signatories']['signatory1']. The second is = which obviously assigns the reference to $cluster.

Upvotes: 1

Related Questions