# Duncan's blog

## October 12, 2014

### Project Euler: problem 40 (PHP) – Champernowne’s constant

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

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

Problem 40:

An irrational decimal fraction is created by concatenating the positive integers:

0.123456789101112131415161718192021…

It can be seen that the 12th digit of the fractional part is 1.

If dn represents the nth digit of the fractional part, find the value of the following expression.

d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000

Code:

```<?php
\$fraction = "";
\$total = 1;

foreach (range(1,1000000) as \$i) {
\$fraction .= \$i;

if (strlen(\$fraction) >= 1000000) {
break;
}
}

\$total *=
substr(\$fraction, 0, 1) *
substr(\$fraction, 9, 1) *
substr(\$fraction, 99, 1) *
substr(\$fraction, 999, 1) *
substr(\$fraction, 9999, 1) *
substr(\$fraction, 99999, 1) *
substr(\$fraction, 999999, 1);

echo \$total;
```

The code is very similar to how I did it in Python and ColdFusion.