Q:

Build array path

I am trying to build array paths to reduce code. The reason is having approximately 50 long paths and I would like to reduce the code base.
For "test-2" the variable "$path" can be hardcoded, meanwhile the right-side "key-X" should be able to be adjusted e.g. for later for-loop.
Question:
Is it possible to build an array path as described in "test-2"?
Wanted result:
Test-1: 60
Test-2: 60
<?php

$arrayWithPrettyLongName = [
  'level_1' => [
    'key_1' => 10,
    'key_2' => 20,
    'key_3' => 30,
  ]
];

// Test-1 // Works fine!

$result_1 =
$arrayWithPrettyLongName['level_1']['key_1'] +
$arrayWithPrettyLongName['level_1']['key_2'] +
$arrayWithPrettyLongName['level_1']['key_3'] ;

echo $result_1;

// Test-2 // Throws errors.

$path = "$arrayWithPrettyLongName['level_1']";

$result_2 =
$path . ['key_1'] +
$path . ['key_2'] +
$path . ['key_3'] ;

echo $result_2;

Error
PHP Parse error:  syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in Xxx.php on line 18

A:

I think what you really want to know here, is how to create an array reference. You can do that by preceding the array name with an ampersand symbol
<?php

$arrayWithPrettyLongName = [
  'level_1' => [
    'key_1' => 10,
    'key_2' => 20,
    'key_3' => 30,
  ]
];

// Test-1 // Works fine!

$result_1 =
$arrayWithPrettyLongName['level_1']['key_1'] +
$arrayWithPrettyLongName['level_1']['key_2'] +
$arrayWithPrettyLongName['level_1']['key_3'] ;

echo $result_1;
echo "\n";

//Just create an array reference here, by preceding the name with an `&`
$path = &$arrayWithPrettyLongName['level_1'];

//Also remove the `.` symbol here. That's not the correct syntax
$result_2 =
$path['key_1'] +
$path['key_2'] +
$path['key_3'] ;

echo $result_2;

But look! If you really want to reduce the code, can't you just do this?
$result_3 = 0;
foreach ($arrayWithPrettyLongName['level_1'] as $value){
    $result_3 += $value;
}
echo $result_3;

Save's a lot of hassle if the array gets bigger later on.

