1

I want to learn how to use recursive functions, so I started to create one:

<?php
$tableau = [[[[2],[2]],[[2],[2]]],[[[2],[2]],[[2],[2]]]];
function test_count_recursive($tab, $compte = 0){
    foreach($tab as $ss_tab){
        if(!is_array($ss_tab)){
            $compte += 1;
        }
        else{
            test_count_recursive($ss_tab, $compte);
        }
    }
    return $compte;
}

echo test_count_recursive($tableau);

But it doesn't work, can you tell me why?

2
  • 2
    Your returning $compte but not using it. Commented Jan 7, 2021 at 19:57
  • Php recursive array counting Commented Nov 2, 2022 at 10:53

1 Answer 1

2

Generally, you pass a piece of data up the recursive call tree or down, not both. In this case, you don't need to pass parent values down. Just return the count and let the parent node accumulate it:

<?php

function test_count_recursive($tab /* one param only */) {
    $compte = 0; // <-- store the local total for this node

    foreach ($tab as $ss_tab) {
        if (is_array($ss_tab)) {
            $compte += test_count_recursive($ss_tab /* one param only */);
            // ^^^^^^^ accumulate total from children
        }
        else {
            $compte++;
        }
    }

    return $compte;
}

$tableau = [[[[2],[2]],[[2],[2]]],[[[2],[2]],[[2],[2]]]];   
echo test_count_recursive($tableau); // => 8
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this feels very counterintuitive for the moment but it's perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.