Combining of decisions (if statement) and looping (foreach loop) in PHP within an HTML document. In this example, we'll use PHP to list of even and odd numbers based on user input:
Here's a simple example that demonstrates the use of decisions (if statement) and looping (for loop) within an HTML document:
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Decision and Looping Example</title>
</head>
<body>
<h1>PHP Decision and Looping Example</h1>
<form action="" method="post">
<label for="userInput">Enter a number:</label>
<input type="number" name="userInput" id="userInput" required>
<input type="submit" value="Generate Numbers">
</form>
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get user input
$userInput = $_POST["userInput"];
// Validate input to ensure it's a positive integer
if (is_numeric($userInput) && $userInput > 0 && $userInput == round($userInput)) {
echo "<h2>Generated Numbers:</h2>";
// Looping: foreach loop to generate even and odd numbers
echo "<p>Even Numbers: ";
for ($i = 0; $i <= $userInput; $i += 2) {
echo "$i ";
}
echo "</p>";
echo "<p>Odd Numbers: ";
for ($i = 1; $i <= $userInput; $i += 2) {
echo "$i ";
}
echo "</p>";
} else {
// Display an error message for invalid input
echo "<p style='color: red;'>Please enter a valid positive integer.</p>";
}
}
?>
</body>
</html>
Output:
In this example:
This example showcases how PHP can be used for decision-making (checking user input) and looping (generating and displaying numbers) within an HTML document.