# Duncan's blog

## October 10, 2014

### Project Euler: problem 34 (PHP) – Digit factorials

Filed under: PHP,Project Euler — duncan @ 8:00 am

I previously blogged about this Project Euler puzzle nearly 6 years ago, using ColdFusion.  This is my approach using PHP as a simple practical exercise for myself, and I’d appreciate any feedback on my PHP code.

Problem 34:

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

Find the sum of all numbers which are equal to the sum of the factorial of their digits.

Note: as 1! = 1 and 2! = 2 are not sums they are not included.

Code:

```<?php
function factorial(\$x) {
\$factorial = 1;

for (\$i = \$x; \$i > 1; \$i--) {
\$factorial *= \$i;
}

return \$factorial;
}

// calculate the factorials from 0 to 9
\$factorials = [];
for (\$i = 0; \$i <= 9; \$i++) {
\$factorials[\$i] = factorial(\$i);
}

\$numbers = [];
\$total = 0;

for (\$i = 3; \$i <= 99999; \$i++) {
\$sum = 0;

// get the factorial of each digit of i
for (\$j = 0; \$j < strlen(\$i); \$j++) {
\$sum += \$factorials[substr(\$i, \$j, 1)];
}

// does i = the sum of the factorials?
if (\$i == \$sum) {
\$numbers[] = \$i;
}
}

foreach(\$numbers as \$i) {
\$total += \$i;
}

echo \$total;
```

I took the same approach as I ended up using with the ColdFusion, where I started out calculating the factorials of all the numbers 0..9, for quick reference later.