erol_smsr erol_smsr -4 years ago 111
PHP Question

Cannot redeclare function() with recursion inside for loop

I have PHP code that looks like this:

function generate_sections() {
$puzzle = [];

// sections
for ($i = 0; $i < 9; $i++) {
// cells
function generate_cells() {
$section = [];

for ($i = 0; $i < 9; $i++) {
$random_number = rand(1, 9);

if (!in_array($random_number, $section)) {
array_push($section, $random_number);
} else {
return generate_cells();
}
}
}

array_push($puzzle, $section);
}

return $puzzle;
}

var_dump(generate_sections());


The second for loop has to generate unique numbers and add them to the sections[] array. This works fine when I take the second for loop out of the first one. However, when writing it like this, the generate_cells() function doesn't recur, it gives me the following error:

Fatal error: Cannot redeclare generate_cells() (previously declared in /Applications/AMPPS/www/sudoku/index.php:38) in /Applications/AMPPS/www/sudoku/index.php on line 37

Answer Source

You are declareting function "generate_cells" in loop. At second loop executing, when function is allready declareted you getting a fatal error.
It's must be like this:

function generate_sections() 
{
    $puzzle = [];

    // sections
    for ($i = 0; $i < 9; $i++) {
        // cells
        $section = generate_cells();

        array_push($puzzle, $section);
    }
    return $puzzle;
}

function generate_cells() 
{
    $section = [];

    for ($i = 0; $i < 9; $i++) {
        $random_number = rand(1, 9);

        if (!in_array($random_number, $section)) {
            array_push($section, $random_number);
        } else {
            return generate_cells();
        }
    }

    return $section;
}

var_dump(generate_sections());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download