PHP code for problem 12 - slow