4. Write an HTML form (see NOTE below -- end of this page on PHP Forms and User Input) that prompts the user to enter a value. In PHP, write a script that uses conditional operator to determine whether a variable contain a number and whether the number is even. You need to use the is_numeric ( ) function and the conditional operator. For floating-point numbers, you need to use the round ( ) function to convert the value to the nearest whole number. Code this program using only conditional operator.
Test the program with the following values
1. a non-numeric value
2. an even #
3. an odd #
4. a number with decimal points
Notes on Problem #4:
The Ternary Operator is a comparison operator commonly found in other programming languages including PHP. It can end up saving you a bit of time and lines of code.
Here is the Format: ( expr1 ) ? ( expr2 ) : (expr3)
**************************************************************
CODES:
<?php
$testValue = $_POST['inputValue'];
if (!isset($_POST['submit'])) {
?>
<p>Enter a value here:<br />
<form action="<?php echo $_SERVER["PHP_SELF"]?>" method="post" />
<input type="text" size="12" maxlength="20" name="inputValue" />
<br />
<input type="submit" value="Submit" name="submit" />
</form><br />
Press the "Submit" button to evaluate the input using the PHP conditional (ternary) operator.
</p>
<?php
} elseif (($testValue !==0) && ($testValue !=="")) {
echo "Hello. Welcome to Martha's test of the ternary operator."."<br />";
echo "The value you submitted was: ".$testValue.".<br />";
echo (is_numeric($testValue) ? "The value entered is a number." :
(is_double($testValue)) && ((round($testValue)%2)==0)) ? "The number '".round($testValue)."' (rounded) is even." : "The value you entered is NOT a number!";
}
?>
**************************************************************
ANSWER:
Enter a value here: