Search code examples
phparraysreferenceassociative-array

Referencing an associative array added as value inside another associative array


I have the following structure:

$positions = array();
$salaries = array();

$registers = ['Position' => $positions, 'Salary' => $salaries];

Since I created the positions and salaries associative arrays at the beginning using the array() syntax I assumed that later in the code I can just write:

$salaries += [$name => $salary];

But found out that at the end when tried to get some data using the registers array: $registers['Position'] or $registers['Salary'] after I've done some filtering everything was empty and I had to reference it via registers to actually put data in:

$registers['Salary'] += [$name => $salary];

or create the registers array later in the code near the end of the script when the other arrays - positions and salaries were already full with the needed data.

My question is - since I put positions and salaries as values inside registers array does that mean I lose the ability to reference them as separate / independent arrays. I created them as described with that purpose in mind and registers array is for filtering purposes and I made it at the beginning so I have all that code at the very top of the script.

Will be very grateful for any info on the matter.


Solution

  • Just posting CBroe's comment as an answer for better visibility.


    $registers = ['Position' => $positions, 'Salary' => $salaries]; simply creates copies of the current content of those arrays at this point. What you want, would require that the elements be added as references instead of copies: $registers = ['Position' => &$positions, 'Salary' => &$salaries]; But there are some cave-ats when working with references, so make sure you understand what is explained under php.net/manual/en/language.references.php properly.