<?php
/**
 * Author: David Mottern
 * This was inspired by Project Euler problem 4.
 * https://projecteuler.net/problem=4
 * It's not meant to be a final polished project.
 *
 * Largest palindrome product
 * Problem 4
 * A palindromic number reads the same both ways.
 * The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
 * Find the largest palindrome made from the product of two 3-digit numbers.
 *
 * I've written a more general solution where you can pass any positive integer n (within reason)
 * and find the largest palindrome made from the product of two n-digit numbers.
 *
 * This is live on the web at http://mottern.com/projecteuler/Problem4/
 * To solve for the problem described, for example, you would call it as follows:
 *      http://mottern.com/projecteuler/Problem4/?length=2
 * This will also work if the values are sent in a Post rather than a Get.
 */

/**
 * Test for palindrome
 *
 * @param $test
 *      An integer or string to be tested.
 *
 * @return boolean
 *      True if the string or number is palindromic,
 *      false otherwise.
 */
function is_palindrome($test) {
    return 
$test == strrev($test) ? True False;
}

/**
 * Find the largest palindrome made from the product of two integers containing $length digits.
 *
 * @param $length
 *      An integer or string to be tested.
 *
 * @return integer
 *      The palindromic integer found
 *      or NAN if no palindrome is found.
 */
function find_largest_palindrome($length) {
    
$largest 0;
    
$min str_pad('1'$length'0');
    for (
$int1 str_pad(''$length'9'); $int1 >= $min$int1--) {
        for (
$int2 $int1$int2 >= $min$int2--) {
            
$product $int1 $int2;
            if (
is_palindrome($product)) {
                if (
$product $largest) {
                    
$largest $product;
                }
            }
        }
    }
    if (
$largest == 0) {
        return 
NAN;
    } else {
        return 
$largest;
    }
}

// Show usage message for both errors and warnings.
set_error_handler("warning_handler"E_WARNING);
function 
warning_handler() {
    throw new 
Exception();
}

// Main Code
try {
    if (isset(
$_REQUEST['show_source'])) {
        
show_source(__FILE__);
        exit ;
    }

    if (!isset(
$_REQUEST['length']) || !is_numeric($_REQUEST['length'])) {
        throw new 
Exception();
    }
    echo 
'The Largest Palindrome is ' find_largest_palindrome($_REQUEST['length']);
} catch (
Exception $e) {
    
//      Show the usage message regardless of the exception type.
    
echo $e '<br>';
    echo 
'usage: <i>index.php?length=x</i> with length being an integer value > 0.';
    echo 
'<br>View PHP source: <A href="http://mottern.com/projecteuler/Problem4/?show_source">http://mottern.com/projecteuler/Problem4/?show_source</A>';
}
?>