Skip to content
Advertisement

Searching element in multidimensional array – using recursion

I want to write own searching function in multilevel array using recursion.

$arr=[923,[123,158,12,[999,998]],111,12];
        function search($arr,$searched){
            static $position;
            static $level=0;
            foreach($arr as $k=>$v){
                if(is_array($v)){
                    $level++;
                    search($v,$searched);
                }
                elseif($v==$searched){
                    $position[]=['level'=>$level,'key'=>$k];
                }
            }
            return dd($position);
        }

Results are incorrect for last 2 elements 111, 12. I get NULL. For the rest it’s ok. What is wrong?

Advertisement

Answer

function search($arr,$searched){
    static $position;
    static $level=0;
    $nextLevelArray = [];
    foreach($arr as $k=>$v){ //first check only integers
        if(is_array($v)){
            $nextLevelArray[] = $v; //save array elements
        } elseif($v==$searched){ //found and save
            $position[]=['level'=>$level,'key'=>$k];
        }
    }
    if(!empty($nextLevelArray)){
        foreach($nextLevelArray as $nextLevelElement){ //check array elements and again and again...
            $level++;
            search($nextLevelElement,$searched);
        }
    }
    return dd($position);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement