I'm trying to guess how to iterate over multi-dimensional arrays with unknown number of dimensions. I've always done that job statically setting foreach statements inside foreach statements but I don't know how many statements to set this time because dimensions number is variable. In summary, All I need is to iterate over every element in a parent array that has more arrays as values and those values that are arrays have more arrays as values, and so on...
            Asked
            
        
        
            Active
            
        
            Viewed 1,537 times
        
    0
            
            
         
    
    
        Aniket Sahrawat
        
- 12,410
- 3
- 41
- 67
 
    
    
        ProtectedVoid
        
- 1,293
- 3
- 17
- 42
- 
                    1_iterate_ and do what? – AbraCadaver Jan 24 '18 at 21:22
- 
                    want to have some fun doing it? http://php.net/manual/en/class.recursivearrayiterator.php – Scuzzy Jan 24 '18 at 21:23
- 
                    @AbraCadaver is that relevant? I just want to get the index of every iterated element. – ProtectedVoid Jan 24 '18 at 21:23
- 
                    1`array_walk_recursive`, `RecursiveArrayIterator`? – Professor Abronsius Jan 24 '18 at 21:23
- 
                    You can simply create a recursive array function which will manage your looping and recursion quite manually, ie call the same function on array children that are also iterable. eg https://stackoverflow.com/questions/2648968/what-is-a-recursive-function-in-php – Scuzzy Jan 24 '18 at 21:24
1 Answers
1
            
            
        Recursion is all that you need:
function recur($arr) {
    if (!is_array($arr)) {
        // $arr is the last element
        echo "$arr ";
        return;
    }
    foreach($arr as $ar) recur($ar);
}
 
    
    
        Aniket Sahrawat
        
- 12,410
- 3
- 41
- 67
- 
                    Much like I use when drilling through a directory of directories... these little self-calling functions are a wonder. – IncredibleHat Jan 24 '18 at 21:26
- 
                    @IncredibleHat Technically speaking, they are called recursive function :) – Aniket Sahrawat Jan 24 '18 at 21:29
- 
                    1Well... yes... I was re-iterating in laymen's terms ;) Thats my story and I'm sticken to it. – IncredibleHat Jan 24 '18 at 21:31