0

Having: an array $a, a variable $indexes = "[\"level1\"][\"level2\"][\"level3\"]";

Is there any way to access $a["level1"]["level2"]["level3"]?

The situation is that the number of indexes that this function will handle can change. So this is the reason the indexes comes in a variable.

Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • Possible duplicate of [use strings to access (potentially large) multidimensional arrays](http://stackoverflow.com/questions/7003559/use-strings-to-access-potentially-large-multidimensional-arrays) – mickmackusa May 10 '17 at 11:02
  • This question is a Super Duplicate. http://stackoverflow.com/search?q=%5Bphp%5D+variable+variables+array+keys – mickmackusa May 10 '17 at 11:16

2 Answers2

0

Hope this simple solution will help you out.

Try this code snippet here

<?php

ini_set('display_errors', 1);

//Here we are retrieving levels
$indexes = '["level1"]["level2"]["level3"]';
preg_match_all('/(?<=")[\w]+(?=")/', $indexes,$matches);
$levels=$matches[0];

//this is the sample array
$array=$tempArray=array(
    "level1"=>array(
        "level2"=>array(
            "level3"=>"someValue"
        )
    )
);
//here we are iterating over levels to get desired output.

foreach($levels as $level)
{
    $tempArray=$tempArray[$level];
}
print_r($tempArray);
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

Firstly, do not use string for $indexes, use an array.

For simple retrieving, you can use array_reduce:

$result = array_reduce($indexes, function ($array, $index) {
    return isset($array[$index]) ? $array[$index] : null;
}, $array);

Note that value defaults to null when there is no such index in the array.

Here is working demo.

If you want some more sophisticated stuff, check out a library I wrote some time ago for situations, when you also need to add items to an array and check for the existence:

var_dump(isset($array[['foo', 'bar']]));

var_dump($array[['foo', 'bar']]);

$array[['foo', 'bar']] = 'baz';

unset($array[['foo', 'bar']]);

They are all valid usage examples for existence checking, retrieving the element, writing the element and deleting the element respectively.

sevavietl
  • 3,762
  • 1
  • 14
  • 21