Introduction:
Learn the fundamentals of PHP programming with the if…elseif…else statements. This comprehensive guide walks you through the syntax, usage, and examples of PHP conditional statements, empowering you to make informed decisions in your code. Explore practical scenarios and enhance your programming skills with step-by-step explanations.”
In PHP, the if…else statements are used to make decisions in your code based on certain conditions.
The basic syntax for an if…else statement is as follows:
if (condition) { // code to be executed if the condition is true } else { // code to be executed if the condition is false }
Here’s a simple example:
$number = 10; if ($number > 0) { echo "The number is positive."; } else { echo "The number is non-positive."; }
In this example, if the value of $number is greater than 0, it will echo “The number is positive.” Otherwise, it will echo “The number is non-positive.”
You can also have multiple conditions using elseif:
$number = 0; if ($number > 0) { echo "The number is positive."; } elseif ($number < 0) { echo "The number is negative."; } else { echo "The number is zero."; }
Here, if $number is greater than 0, it echoes “The number is positive.” If it’s less than 0, it echoes “The number is negative.” Otherwise, it echoes “The number is zero.”
You can nest if…else statements to handle more complex conditions:
$grade = 75; if ($grade >= 90) { echo "A"; } elseif ($grade >= 80) { echo "B"; } elseif ($grade >= 70) { echo "C"; } elseif ($grade >= 60) { echo "D"; } else { echo "F"; }
In this example, the code determines the letter grade based on the numeric grade. Adjust the conditions as needed for your specific use case.
A Complete example in html with explanation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Discount Calculator</title> </head> <body> <?php // Define variables $purchaseAmount = isset($_POST['purchase_amount']) ? $_POST['purchase_amount'] : ''; $discount = 0; // Check if the form is submitted if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Validate and process the form data if (is_numeric($purchaseAmount)) { // Determine the discount based on the purchase amount if ($purchaseAmount >= 100) { $discount = 0.1 * $purchaseAmount; // 10% discount } else { $discount = 0; // No discount for amounts less than 100 } } else { echo '<p style="color: red;">Please enter a valid numeric amount.</p>'; } } ?> <h2>Discount Calculator</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>"> <label for="purchase_amount">Enter Purchase Amount:</label> <input type="text" name="purchase_amount" id="purchase_amount" value="<?php echo $purchaseAmount; ?>"> <input type="submit" value="Calculate Discount"> </form> <?php // Display the result if ($discount > 0) { $discountedAmount = $purchaseAmount - $discount; echo '<p style="color: green;">Congratulations! You got a ' . number_format($discount, 2) . ' discount. Your discounted amount is: ' . number_format($discountedAmount, 2) . '</p>'; } ?> </body> </html>
Explanation:
HTML Form: The HTML form takes user input for the purchase amount.
PHP Code: The PHP code starts by checking if the form has been submitted ($_SERVER[‘REQUEST_METHOD’] === ‘POST’). It then validates the user input and calculates the discount based on the purchase amount using if…else statements.
Result Display: If a discount is applicable ($discount > 0), it calculates the discounted amount and displays a message with the discount and the discounted amount.
Validation: It checks if the entered purchase amount is a valid numeric value using is_numeric().
Security Note: The form action (action=”<?php echo htmlspecialchars($_SERVER[‘PHP_SELF’]); ?>”) helps prevent potential security vulnerabilities like Cross-Site Scripting (XSS) by escaping the form action URL.
This example demonstrates a simple use case, and you can modify it based on your specific requirements.
Here’s an example to illustrate how it works:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Grade Calculator</title> </head> <body> <?php // Assume a student's score $score = 85; // Using if...elseif...else to determine the grade if ($score >= 90) { $grade = 'A'; } elseif ($score >= 80) { $grade = 'B'; } elseif ($score >= 70) { $grade = 'C'; } elseif ($score >= 60) { $grade = 'D'; } else { $grade = 'F'; } ?> <h2>Grade Calculator</h2> <p>The student's score is <?php echo $score; ?>.</p> <?php // Display the grade echo '<p>The student\'s grade is: ' . $grade . '</p>'; ?> </body> </html>
Explanation:
HTML Structure: The HTML structure is basic and includes a title, a heading, and placeholders for displaying the score and grade.
PHP Code: The PHP code initializes a variable $score with a hypothetical student’s score. The if…elseif…else statement is then used to determine the corresponding grade based on the score.
Grade Calculation: The conditions are structured in decreasing order of score ranges. If a condition is met, the corresponding grade is assigned. If none of the conditions are met, the default is an ‘F’ grade.
Display Result: The final grade is then displayed in the HTML.
This example can be adapted for various scenarios where you need to evaluate multiple conditions and execute different code blocks based on those conditions. Adjust the score values and grade ranges as needed for your specific use case.
Create three files for this application:
index.php (Main page with the form)
process.php (Handles form submission and grade calculation)
styles.css (Stylesheet for a bit of visual appeal)
1. index.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Grade Calculator</title> </head> <body> <div class="container"> <h2>Grade Calculator</h2> <form action="process.php" method="post"> <label for="score">Enter Exam Score:</label> <input type="text" name="score" id="score" required> <button type="submit">Calculate Grade</button> </form> </div> </body> </html>
2. process.php
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Get the score from the form $score = isset($_POST['score']) ? intval($_POST['score']) : 0; // Using if...elseif...else to determine the grade if ($score >= 90) { $grade = 'A'; } elseif ($score >= 80) { $grade = 'B'; } elseif ($score >= 70) { $grade = 'C'; } elseif ($score >= 60) { $grade = 'D'; } else { $grade = 'F'; } // Display the result echo '<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Grade Calculator - Result</title> </head> <body> <div class="container"> <h2>Grade Calculator - Result</h2> <p>Your exam score: ' . $score . '</p> <p>Your grade: ' . $grade . '</p> <a href="index.php">Go back</a> </div> </body> </html>'; } else { // Redirect to the main page if accessed directly header("Location: index.php"); exit(); } ?>
3. styles.css
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; } .container { max-width: 600px; margin: 50px auto; background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } form { display: flex; flex-direction: column; } label { margin-bottom: 10px; } input { padding: 10px; margin-bottom: 20px; } button { padding: 10px; background-color: #4caf50; color: #fff; border: none; border-radius: 4px; cursor: pointer; } button:hover { background-color: #45a049; } a { display: block; margin-top: 20px; color: #4caf50; text-decoration: none; } a:hover { text-decoration: underline; }
Instructions:
To run the app, you need a web server with PHP support. If you don’t have a web server installed locally, you can use tools like XAMPP, MAMP, or WampServer.
Here are general steps to run the app using XAMPP, a widely used solution:
Using XAMPP:
Download and Install XAMPP:
Download XAMPP from the official website: XAMPP.
Follow the installation instructions for your operating system.
Start the Apache Server:
After installation, start the XAMPP control panel.
Click on the “Start” button next to Apache to start the Apache server.
Place Files in htdocs:
Locate the “htdocs” folder within the XAMPP installation directory (e.g., C:\xampp\htdocs on Windows).
Place the three files (index.php, process.php, and styles.css) in this folder.
Access the App:
Open your web browser and go to http://localhost/index.php.
You should see the form for entering the exam score.
Submit Score:
Enter a numeric score, click the “Calculate Grade” button, and you’ll be redirected to the result page.
Notes:
If you encounter any issues, check the XAMPP documentation or the documentation of the specific web server you are using.
Ensure that PHP is properly configured and enabled on your server.
Make sure to enter valid numeric scores in the input field.
Adjust file permissions if needed to ensure that the web server has the necessary permissions to read and execute the PHP files.
Remember, these are general instructions, and specific details may vary depending on your operating system and web server configuration.
We’ll provide you with 15 quiz questions related to PHP and the if…elseif…else statement.
Quiz Questions:
A. To create loops
B. To handle multiple conditions
C. To define functions
D. To include external files
A. It is used to start a new block of code.
B. It is used to handle an alternative condition when the if condition is false.
C. It is used to terminate the program.
D. It is used to define a function.
A. It defines a new variable.
B. It is a placeholder in the code.
C. It introduces an alternative condition to be checked if the previous if or elseif condition is false.
D. It is used to comment out code.
A. if { } elseif { } else { }
B. if () { } elseif () { } else () { }
C. if () { } elseif () { } else { }
D. if { } elseif () { } else { }
A. The server’s IP address
B. The request method used to access the page (e.g., GET or POST)
C. The server’s operating system
D. The server’s current time
A. $_SERVER[‘REQUEST_METHOD’]
B. $_POST[‘score’]
C. if ($score >= 90)
D. echo ‘Your grade is: ‘ . $grade
A. The application crashes.
B. An error message is displayed.
C. The program continues without any issue.
D. The entered value is automatically converted to a numeric type.
A. It calculates the discount.
B. It validates form data.
C. It escapes HTML entities to prevent XSS attacks.
D. It defines a new variable.
A. process.php
B. index.php
C. styles.css
D. There is no HTML form in the application.
A. Handling form submissions
B. Defining PHP functions
C. Providing styling for a more visually appealing interface
D. Calculating grades
A. To terminate the PHP script execution.
B. To create an infinite loop.
C. To restart the Apache server.
D. To hide error messages.
A. By refreshing the browser.
B. By clicking the “Calculate Grade” button again.
C. Automatically after submitting the form.
D. By accessing the result.php file.
A. The discount amount
B. The user’s exam score
C. The calculated grade based on the score
D. The total purchase amount
A. The background color of the HTML body
B. The background color of the form
C. The color of the grade text
D. The color of the submit button
A. It defines the button’s color.
B. It defines the button’s background color when hovered over.
C. It defines the button’s border.
D. It defines the font size of the button text.
Answers:
1-B, 2. B, 3. C, 4. C, 5. B, 6. B, 7. B, 8. C, 9. B, 10. C, 11. A, 12. C, 13. C, 14. B, 15. B