Search code examples
phparraysrecursion

Self calling array return php


i am writing a module that sorts through categories and returns me the lowest possible subcategory.

private function getChild($array){
    foreach($array as $item){
        if(is_array($item)){
            $this->getChild($item);
        } else {
            array_push($this->catsToReturn, $item);
        }
    }
}

So my actual issue and question is why can't i return value in else enclosure? I would like to return $item and push that value to array, that would give me a better code readability, since now i have

$this->getChild($this->postCategories);

Hanging randomly in my code.

The strange and new thing for me is that i can echo the value but i can't return it, i know it's an issue with scope, but can't find any info on how to solve it.

Just wanted to know how to improve this.

Cheers


Solution

  • You could change your code by adding $item in an array and doing an array_merge to take results from subsequent calls.

    <?php
    
    private function getChild($array){
        $result = [];
        foreach($array as $item){
            if(is_array($item)){
                $result = array_merge($result,$this->getChild($item));
            } else {
                $result[] = $item;
            }
        }
    
        return $result;
    }
    

    From wherever you are calling in your class, you can just do

    $this->catsToReturn = $this->getChild($array)