Here is another option: Create a temporary parsable string (by extracting the first value, then appending the remaining values as square bracket wrapped strings), call parse_str(), and set the output variable as $bar.
Code: (Demo)
$foo = ['a', 'b', 'c'];
$val=123;
parse_str(array_shift($foo).'['.implode('][',$foo)."]=$val",$bar);
// built string: `a[b][c]=123`
var_export($bar);
Output:
array (
'a' =>
array (
'b' =>
array (
'c' => '123',
),
),
)
If that first method feels too hack-ish, the following recursive method is a stable approach:
Code: (Demo)
function nest_assoc($keys,$value){
return [array_shift($keys) => (empty($keys) ? $value : nest_assoc($keys,$value))];
// ^^^^^^^^^^^^^^^^^^--------------------------------------------------------extract leading key value, modify $keys
// check if any keys left-----^^^^^^^^^^^^
// no more keys, use the value---------------^^^^^^
// recurse to write the subarray contents-------------^^^^^^^^^^^^^^^^^^^^^^^^^
}
$foo=['a','b','c'];
$val=123;
var_export(nest_assoc($foo,$val));
// same output
['a', 'b', 'c', 'd'];would that make the output$bar['a']['b']['c']['d']? And would it still be 123? Or 1234?