// look for no POST entries, or the RESET button
if (count($_POST) == 0 or @$_POST['reset']) {
// POST array is empty - set initial values
$principal = null;
$number = null;
$rate = null;
$payment = null;
} else {
// retrieve values from POST array
$principal = $_POST['principal'];
$number = $_POST['number'];
$rate = $_POST['rate'];
$payment = $_POST['payment'];
} // if
// validate all fields
$error = array();
if (!empty($principal)) {
if (!is_numeric($principal)) {
$error['principal'] = "must be numeric";
} elseif ($principal < 0) {
$error['principal'] = "must be > zero";
} else {
$principal = (float)$principal; // convert to floating point
} // if
} // if
if (!empty($number)) {
if (!ereg('^[[:digit:]]+$', $number)) {
$error['number'] = "must be an integer";
} else {
$number = (int)$number; // convert to integer
} // if
} // if
if (!empty($rate)) {
if (!is_numeric($rate)) {
$error['rate'] = "must be numeric";
} elseif ($rate < 0) {
$error['rate'] = "must be > zero";
} else {
$rate = (float)$rate; // convert to floating point
} // if
} // if
if (!empty($payment)) {
if (!is_numeric($payment)) {
$error['payment'] = "must be numeric";
} elseif ($payment < 0) {
$error['payment'] = "must be > zero";
} else {
$payment = (float)$payment; // convert to floating point
} // if
} // if
if (count($error) == 0) {
// no errors - perform requested action
if (isset($_POST['button1'])) {
$principal = calc_principal($number, $rate, $payment);
} // if
if (isset($_POST['button2'])) {
$number = calc_number($principal , $rate, $payment);
} // if
if (isset($_POST['button3'])) {
$rate = calc_rate($principal, $number, $payment);
} // if
if (isset($_POST['button4'])) {
$payment = calc_payment($principal, $number, $rate ,2);
} // if
} // if
function calc_principal ($payno, $int, $pmt)
{
// check that required values have been supplied
if (empty($payno)) {
echo "
a value for NUMBER of PAYMENTS is required
"; exit; } // if if (empty($int)) { echo "a value for INTEREST RATE is required
"; exit; } // if if (empty($pmt)) { echo "a value for PAYMENT is required
"; exit; } // if // now do the calculation using this formula: //****************************************** // ((1 + INT) ** PAYNO) - 1 // PV = PMT * -------------------------- // INT * ((1 + INT) ** PAYNO) //****************************************** $int = $int / 100; //convert to percentage $value1 = (pow((1 + $int), $payno)) - 1; $value2 = $int * pow((1 + $int), $payno); $pv = $pmt * ($value1 / $value2); $pv = number_format($pv, 2, ".", ""); return $pv; } // calc_principal ================================================================== function calc_rate($pv, $payno, $pmt) { // try and guess the value using binary chop technique $GuessHigh = (float)100; // maximum value $GuessMiddle = (float)2.5; // first guess $GuessLow = (float)0; // minimum value $GuessPMT = (float)0; // result of test calculation