Search code examples
phparraysjsonobjectphp-8

Is there a way to dynamically access multidimensional PHP array?


Is there a way to access a PHP multidimensional array (specific index) dynamically?

So for example, say I want to access a value at:

$array[1]['children'][0]['children'][2]['settings']['price']

Can there be a function which returns this value by just getting index (1, 0 and 2 respectively)? and in a way that it works whether there are 3 values (1, 0 and 2) or more.

SO for example , we call function "getArrayValue()" and we can it like so:

getArrayValue('1,0,2')

this should return $array[1]['children'][0]['children'][2]['country']['city']

or in case of 2 values getArrayValue('1,0') should return $array[1]['children'][0]['country']['city']

so basically, the issue I am facing is needing help with dynamically building the query to get array value...

Or if there is a way to convert a string like $array[1]['children'][0]['country']['city'] and evaluate it to get this value from the array itself?

Another way to explain my problem:

$arrayIndex = "[1]['children'][0]";
$requiredValue = $array[1] . $arrayIndex . ['country']['city'];

//// so $requiredValue should output the same value as the below line would:
$array[1]['children'][0]['children'][2]['country']['city'];

Is there a way to achieve this?


Solution

  • In your case you will need something like this:

    <?php
      
    
    function getArray($i, $j, $k, $array) {
        if (isset($array[$i]['children'][$j]['children'][$k]['country']['city']))
        {
            return $array[$i]['children'][$j]['children'][$k]['country']['city'];
        }
    }
    
    $array[0]['children'][0]['children'][0]['country']['city'] = "some value";
    $array[0]['children'][0]['children'][1]['country']['city'] = "another";
    $array[0]['children'][1]['children'][1]['country']['city'] = "another one";
    .
    .
    .
    etc
    
    
    echo getArray(0,0,0, $array) . "\n"; // output -> "some value"
    echo getArray(0,0,1, $array) . "\n"; // output -> "another"
    echo getArray(0,1,1, $array) . "\n"; // output -> "another one"
    

    Another thing to keep in mind is that you have called the function passing only one parameter. And your multidimensional array needs at least three.

    getArrayValue('1,0,2')
    

    You have to take into account that you have called the function passing only one parameter. Even if there were commas. But it's actually a string.

    getArrayValue(1,0,2) //not getArrayValue('1,0,2') == string 1,0,2
    

    If you want to pass two values, you would have to put at least one if to control what you want the function to execute in that case. Something like:

      function getArray($i, $j, $k, $array) {
        if($k==null){
            if(isset($array[$i]['children'][$j]['country']['city'])){
                return $array[$i]['children'][$j]['country']['city']; //
            }
        } else {
            if(isset($array[%i]['children'][$j]['children'][$k]['country']['city'])){
                return $array[$i]['children'][$j]['children'][$k]['country']['city'];
            }
        }
    }
    
    getArray(0,0,null, $array) 
    getArray(0,0,1, $array) 
    

    For the last question you can get by using the eval() function. But I think it's not a very good idea. At least not recommended. Example:

    echo ' someString ' . eval( 'echo $var = 15;' );
    

    You can see the documentation: https://www.php.net/manual/es/function.eval.php

    edit: I forgot to mention that you can also use default arguments. Like here.

    <?php
    
    $array[0]['children'][0]['children'][0]['country']['city'] = "some value";
    $array[0]['children'][0]['children'][1]['country']['city'] = "another";
    $array[0]['children'][1]['children'][1]['country']['city'] = "another one";
    
    function getArray($array,$i, $j, $k = null) {
        if($k==null){
            echo 'getArray called without $k argument';
            echo "\n";
        } 
        else{
            echo 'getArray called with $k argument';
            echo "\n";
        }
       
    }
    
    getArray($array,0,0);    //here you call the function with only 3 arguments, instead of 4
    getArray($array,0,0,1);
    

    In that case $k is optional. If you omit it, the default value will be null. Also you have to take into account that A function may define default values for arguments using syntax similar to assigning a variable. The default is used only when the parameter is not specified; in particular, note that passing null does not assign the default value.

    <?php
    function makecoffee($type = "cappuccino"){
        return "Making a cup of $type.\n";
    }
    echo makecoffee();
    echo makecoffee(null);
    echo makecoffee("espresso");
    

    The above example will output:

    Making a cup of cappuccino.
    Making a cup of .
    Making a cup of espresso.
    

    You can read more about that here: https://www.php.net/manual/en/functions.arguments.php