HomeWriters RSS

Coding Challenge #1

The Task

Write some code in PHP that prints the numbers 0-1000-0 on a new line. Ensuring it is the fastest code possible.


Below is a list of the solutions in the order that they were received, along with the person that submitted them.

Two For Loops - @michaelw90

for($i = 0; $i < 1001; $i++){
    echo $i . '<br />';
for($i = 999; $i > -1; $i--){
    echo $i . '<br />';

Two Range Loops - @michaelw90

foreach(range(0,1000) as $n){
    echo $n . '<br />';
foreach(range(999, 0) as $n){
    echo $n . '<br />';

One Merged Range Loop - @michaelw90

foreach(range(0,1000) + range(999, 0) as $n){
    echo $n . '<br />';

Recursive Output - @returnwt

function a($a, $b){
    return ($a == $b) ? $b : $a . '<br />' . a($a+1,$b) . '<br />' . $a;
echo a(0,1000);

Range Popping - @jcsrb

$a = range(0, 1000);
function p($a){
    foreach($a as $n){
        echo $n . "<br/>";

Range Walking - @chadtomkiss

function display($val){
    echo $val . '<br />';
$values = range(0,1000);
$reverse = array_reverse($values);
array_walk($values, 'display');
array_walk($reverse, 'display');

Range Function Echo - @jcsrb

foreach(range(0, 999) as $n){
    $a = $a . $n . "<br/>";
    $b = $b . (999-$n) . "<br/>";


A very interesting experiment showing people's thoughts about how to arrive at the solution. Most people opting to use the range() method, however this probably has a large amount of overhead with it compared to using a simple for loop up to 1k.

If you have a better solution, simply add it in the comments below (PHP only please), and I'll get it added to the article.

I will soon be writing a quick page to run some performance tests of these to allow us to find out (from a large number of people) which runs quickest on average - watch this space!