Slightly optimized PHP solution to Problem 1.