2

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.

4
  • This is not possible. You could rather play with references. Commented Mar 18, 2021 at 8:39
  • @nice_dev Do you know any idea ? Commented Mar 18, 2021 at 8:41
  • Any reason why to not use standard approach? Basic PHP syntax? echo $array['settings']['app'] is shorter than $handle = ...'; echo $array[$handle]... Commented Mar 18, 2021 at 8:42
  • @pavel i have a function that fetches data by typing keynames like this : get('settings|app') this getting $array['settings']['app']; Commented Mar 18, 2021 at 8:45

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Hothaifajaber: it should works independently on nested level - string xxx|yyy|zzz for 3D array should return correct value. You can try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.