PHP mostly works, but has a weird issue

I am working on a class assignment where we need to pick a formula with two or more variables and write a script to solve the formula after inputting the variables. I chose the quadratic formula because it’s my favorite. I want it to post a message when non-numeric values are inputted or left blank and a different message if the A variable is zero. The first error message works, but it still displays that message when A = 0. I am using elseif for the A = 0 condition, but it seems to just skip this. Here is my code:

// Gets the data from the form
$avar = $_POST[‘avar’];
$bvar = $_POST[‘bvar’];
$cvar = $_POST[‘cvar’];

// This solves for x

 if ( empty($avar) or empty($bvar) or empty($cvar) || !is_numeric($avar) or !is_numeric($bvar) or !is_numeric($cvar)) {
 $answer = 'All variables must be numbers.';
 include('index.php');
 exit();

}

else if ( $avar == 0 ) {
$answer = ‘This is a linear equation, not a quadratic equation.’;
include(‘index.php’);
exit();
}

else {
$radical = pow($bvar, 2) - (4 * $avar * $cvar);
$denom = 2 * $avar;
$numer1 = -($bvar) + sqrt($radical);
$numer2 = -($bvar) - sqrt($radical);
$xans1 = $numer1 / $denom;
$xans2 = $numer2 / $denom;

// This shows the results

 $answer = 'x = '.number_format($xans1, 2).', '.number_format($xans2, 2);

 }

Sorry for the poor formatting. I’ll fix it.

Okay, I figured it out. Instead of “empty($avar)” etc… I should be using “$avar === FALSE”. I made this correction and now it works as intended. I hope this helps someone else.

Oh, I also deleted the “include/exit” portion after each condition and instead, put it at the end. I replaced the conditional $answer with its own variable $error_message. Not sure if this was necessary, but it looks nicer.

Sponsor our Newsletter | Privacy Policy | Terms of Service