To check if a number is positive or negative in PHP using an HTML form, you can create a simple web page that takes input from the user through a form and then processes that input in PHP. Here’s an example of how you can do this:
- Create an HTML form (
index.html):<!DOCTYPE html> <html> <head> <title>Positive/Negative Number Checker</title> </head> <body> <h1>Positive/Negative Number Checker</h1> <form method="post" action="check_number.php"> <label for="number">Enter a number: </label> <input type="number" name="number" id="number" required> <button type="submit">Check</button> </form> </body> </html>
- Create a PHP script (
check_number.php) to process the form input and check if the number is positive or negative:<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { // Get the user input from the form $number = $_POST["number"]; // Check if the number is positive, negative, or zero if ($number > 0) { $result = "The number $number is positive."; } elseif ($number < 0) { $result = "The number $number is negative."; } else { $result = "The number $number is zero."; } } ?> <!DOCTYPE html> <html> <head> <title>Positive/Negative Number Checker</title> </head> <body> <h1>Result</h1> <?php if (isset($result)) : ?> <p><?php echo $result; ?></p> <?php else : ?> <p>No input received.</p> <?php endif; ?> <a href="index.html">Go back</a> </body> </html>
Here’s how this works:
- The
index.htmlfile contains a form with an input field where the user can enter a number. When the user submits the form, it sends the input to thecheck_number.phpscript for processing. - In
check_number.php, we check if the request method isPOST, which indicates that the form has been submitted. We retrieve the user input using$_POST["number"]. - We then use PHP to check if the number is positive, negative, or zero, and store the result in the
$resultvariable. - Finally, we display the result on the web page along with a link to go back to the input form.
To use this code, save the HTML code in an index.html file and the PHP code in a check_number.php file in the same directory. Open the index.html file in your web browser, enter a number in the form, and click “Check” to see the result.