Search code examples
phploopsforeachnested-loops

increment $x across multiple nesting loops


To list all categories on my website I iterate through category hierarchy with the following function:

$x = 1;
function list_categories($categories, $x) {
    foreach($categories as $category) {
        $cat_list .= '<li>'.$category['name'].'<li>';
        if (count($category['children']) > 0) {
            $cat_list .= '<ul>'
            list_categories($category['children'], $x);
            $cat_list .= '</ul>'
        }
        $x++; // incremention of $x
    }
}

The problem is that $x is incremented in the following manner:

// ITERATION #1
parent: $x = 1
|   // nesting loop #1
|--> child $x = 2
    |   // sub-nesting loop #1
    |--> descendant $x = 3

// ITERATION #2
parent: $x = 2
|   // nesting loop #2
|--> child $x = 3
    |   // sub-nesting loop #2
    |--> descendant $x = 4

// ITERATION #3
parent: $x = 3
|   // nesting loop #3
|--> child $x = 4
    |   // sub-nesting loop #3
    |--> descendant $x = 5

How can I make $x to increment in straight sequence (e.g. 1,2,3,4,5,6,7,8,9,10) across all loops both parent and nesting?


Solution

  • You need to make $x a reference parameter, so that assigning it in the function updates the caller's variable.

    function list_categories($categories, &$x) {