I have an array which contains the path
to a specific value from an other array, to make it a bit more clear, here is an exemple.
My array containing the keys which I'll call $params
Array
(
[0] => paths
[1] => assets
[2] => js
)
And here is my associative array which I'll call $config
Array
(
[paths] => Array
(
[assets] => Array
(
[js] => /assets/js
[css] => /assets/css
)
)
[library] => Array
(
[js] => jQuery
)
)
So how could I use my array 1 to access the value in my array 2?
I tried $config[$params[0]][$params[1]][$params[2]]
, but it's not efficient at all.
Hi Jonathan here you have missed one brace in the end try this "$config[$params[0]][$params[1]][$params[2]]". It will work I am posting a code which worked fine for me
A loop should solve your problem:
This will iterate over every entry in
$params
and then access the subkey of the$config
array. After finding it,$c
will contain the current subarray. In the end,$c
will contain the value you were looking for (NULL
if the path was invalid/not found).The same can be done in a functional way using the
array_reduce
function:You can try
Output