Alok Rai Alok Rai - 3 months ago 15
PHP Question

Recursion function's variable value not changing in PHP

I want to print 1 to 10 numbers using recursion but its not working.

CODE

function table($num1) {
if( $num1 <= 10 ) {
echo $num1;
echo "<br>";
table($num1++);
}

}

$num = 1;
table($num);


Here's the error


Fatal error: Maximum function nesting level of '256' reached,
aborting!


But when I am declaring
$num1
as global its working fine. Please anyone tell me the reason behind it.

Answer

table($num1++) means please pass $num1 to table(), and then increase it by one. So this is not what you want.

You have to write table(++$num1) instead. It means increase $num1 first, then pass it to table().

Comments