Vahid Alvandi
Vahid Alvandi

Reputation: 612

how i can return a value after end recursive function in php

I need after the end of a loop in a recursive function to return the $build variable

This is my code:

    $traverse = function ($tree,$build = '') use (&$traverse) {

        foreach ($tree as $key=>$menu) {
            if (count($menu->children) > 0) {
                $build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a><ul>";
                    $traverse( $menu->children,$build);
                $build .= "</ul></li>";
            } else {
                $build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a></li>";
            }
        }
    };


 $traverse($tree );

Upvotes: 0

Views: 96

Answers (1)

sklwebdev
sklwebdev

Reputation: 281

Regarding my comment u should have:

$traverse = function ($tree) use (&$traverse) {

    $build = '';
    if (count($menu->children) > 0) {
        $build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a><ul>";
        $build .= $traverse($menu->children);
        $build .= "</ul></li>";
    } else {
        $build .= "<li ><a href='" . $menu->url . "'>" . $menu->text . "</a></li>";
    }

    return $build;
};

As u can see u also don't need to pass and use $build as argument to the function.

Also u should check the html code for being valid at the end. Because of it won`t be.

Upvotes: 1

Related Questions