Search code examples
phparraysmultidimensional-array

How to access a deeply nested value in a multidimensional array?


I have an array that looks like this:

Array
(
    [id] => 01
    [name] => johndoe   
    [fields] => Array
        (
             [19] => Array
                 (
                      [othername] => fieldname
                 )
        )
)

How can I go about getting the value from othername?

I tried:

 $array = array();
 $array[fields] = array();
 echo $array[19]['othername'] ;

But I think I need to go down another level?


Solution

  • $array = array();         //-| 
                              // | This resets the variable to blank array. Remove it.
    $array[fields] = array(); //-|
    
    // assuming that variable dumped is $array, directly use this.
    echo $array['fields'][19]['othername'];
    

    But, I would suggest that, you should not fetch the required value using such fix syntax. My answer is just to solve your issue at hand. Implementing coding best practices is out of scope for this answer. You should try to loop recursively and fetch required value.