mayur mayur - 3 years ago 50
PHP Question

Function prints an array but returning null when called php

I have following function which helps me get category name.

public function getParent($categoryId, $keepData) {
$parentCategory = Category::select('category_id', 'parent_id', 'title')
->where('category_id', $categoryId)->first();

if($parentCategory->parent_id > 0) {
$parent = Category::select('category_id','parent_id','title')
->where('category_id',$parentCategory->parent_id)
->first();
$keepData[$parent->category_id] = $parent->title;
$this->getParent($parent->category_id, $keepData);
} else {
//print_r($keepData);
return $keepData;
}
}


When I do
print_r
inside function it prints an array.

array:2 [▼
3 => "Stock Boxes"
1 => "Boxes"
]


but calling this function from other function as,

$keepData = array();
$breadcrumb = $this->getParent($categoryId, $keepData);
print_r($breadcrumb);


then it returns
null
.

What is the step I am missing. any help would be great.

Answer Source

Apparently this condition

if ($parentCategory->parent_id > 0) {
    // ...
} 

evaluates to true, and in this block you are not returning anything, that's why the method invocation effectively returns null.

Adjust the method to

public function getParent($categoryId, array $keepData = [])
{
    $parentCategory = Category::select('category_id', 'parent_id', 'title')->where('category_id', $categoryId)->first();

    if ($parentCategory->parent_id > 0) {
        $parent = Category::select('category_id','parent_id','title')->where('category_id',$parentCategory->parent_id)->first();
        $keepData[$parent->category_id] = $parent->title;

        return $this->getParent(
            $parent->category_id, 
            $keepData
        );
    } 

    return $keepData;
}

and invoke like this (note how $keepData is turned into an optional parameter and defaults to an empty array):

$breadcrumb = $this->getParent($categoryId);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download