Calling values from an array using an array or string - php

Viewed 37

I have a problem writing a code in which I can arrive at the values, but using text or an array

Suppose this Array:

$array = [
    'name' => 'any Name',
    'settings' => [
            'app' => 'Spy',
            'location' => 'Earth',
            'locale' => 'en'
    ]
];

and i want to get app value

default code:

echo $array['settings']['app'];

But this method is not working because I cannot write the parentheses [] [] in my case

I want a method similar to this:

$handle = 'app, name';
echo $array[$handle] ; 

or

$handle = ['settings']['app'];

echo $array[$handle];

I know that the code is wrong, but an example

I hope that the idea has arrived and that there is a solution.

1 Answers

Could it be something like that?

<?php

$array = [
    'name' => 'any Name',
    'settings' => [
            'app' => 'Spy',
            'location' => 'Earth',
            'locale' => 'en'
    ]
];

$str = 'settings|app'; // this is string you have

foreach (explode('|', $str) as $key) {
    if (!isset($output)) {
        $output = $array[$key];
    } else {
        $output = $output[$key];    
    }
}

echo $output; // spy
Related