PHP to 1000 without conditionals and loops

Earlier today I stumbled on a Stackoverflow challenge where the poster asked for C/C++ code that would count from 1 to 1000 without using conditionals or loops. There are some crazy examples in there and I wont presume to understand even half of them.

So when I just now noticed how Justin Vincent at Pluggio had done the same in PHP, my interest sparked. A moment later I now have my own code to meet the challenge.

ini_set('xdebug.max_nesting_level', 1002);
function x($i) { echo "$i\n"; @x(++$i); }
x(1);

It leverages the built-in protection for infinite loops, max_nesting_level. You have probably seen the error before some time, when going too wild on recursive functions.

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

I set the max nesting level to just above what I need and then, using error supression (the @ character), I make sure the fatal error does nothing else but silently kill the program.

So there you have it, counting from 1 to 1000 in PHP without using conditionals or loops!

Update: Stackoverflow now has a post up with this challenge.

Update: Be sure to check out Andrew Curioso’s excellent solution to the problem.

Published