A
A
alestro2016-04-21 17:59:23
PHP
alestro, 2016-04-21 17:59:23

How to access array element dynamically?

Let's say we have an array that has unlimited nesting. And you need to check if there is one or a certain key in the array along the specified path. Approximately as follows: the path for the desired key is passed to the function, let's say user.ivanov matches$array['user']['ivanov']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
ThunderCat, 2016-04-21
@alestro

and what is needed? The question is still somehow crookedly set, or it is not clear how to check?

function checkKey($path,$arr){
$keys = explode(".",$path);
    foreach ($keys as $key){
        if(isset($arr["$key"]))$arr = $arr["$key"];
        else return false;
    }
return true;
}

A
Andrey Minisol, 2016-04-21
@AmadeyMinisol

an example of an array and an example of a key, I didn’t understand a little why we can’t immediately access the key?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question