PHP - gregorymorrison/euler1 GitHub Wiki

I decided to try my hand at PHP, a web programming language introduced in 1995. I hadn't spent any significant with this language before although I have done ASP and JSP, so I figured it couldn't be that hard. I was right - this language is dead-simple. It took me five minutes to bang this version of Euler1 out, including time to install.

The following is what I believe is idiomatic PHP. The language seems to have no facility for the functional paradigm - just straight imperative, folks. I saved the solution into a local variable, $result, so that I could demonstrate variable substitution in PHP's templating engine.

#!/usr/bin/php -q
<?php// Euler1 in PHP

function euler1($n) {
    $sum = 0;

    for ($i=0; $i<$n; $i++) {
        if ($i%3 == 0 || $i%5==0) {
            $sum += $i;
        }
    }
    return $sum;
}

$result = euler1(1000);
?>
Euler1 = <?php echo $result . "\n" ?>

I thought I would have to set up a web server to test this code, but I was surprised to find that PHP has a command-line interpreter. PHP can actually be used as a general-purpose scripting language if that floats your boat. To run this code, I simply installed PHP and then called my script:

$ ./euler1.php
Euler1 = 233168