Of course! Here are the five PHP code examples with numbering and explanations for each.
1. Program to Display "Hello, World!"
This is the most basic PHP script. It uses the echo statement to output the string "Hello, World!" to the browser.
<?php
// This line prints the string to the webpage.
echo "Hello, World!";
?>
2. Program to Declare a Variable and Display its Value
This script demonstrates how to declare a variable in PHP (using the $ sign) and how to display its content using echo.
<?php
// Declare a variable named $message and assign a string value to it.
$message = "Learning PHP is fun!";
// Display the value stored in the $message variable.
echo $message;
?>
3. Program to Add Two Numbers
This program initializes two variables with numeric values, adds them together using the + operator, stores the result in a third variable, and then displays the result in a user-friendly sentence.
<?php
// Declare two number variables.
$num1 = 25;
$num2 = 10;
// Add the two numbers and store the result in the $sum variable.
$sum = $num1 + $num2;
// Display the result using string concatenation (the . operator).
echo "The sum of " . $num1 . " and " . $num2 . " is: " . $sum;
?>
4. Program to Check if a Number is Even or Odd
This script uses an if...else statement to perform a check. The modulo operator (%) calculates the remainder of a division. If a number divided by 2 has a remainder of 0, it is even; otherwise, it is odd.
<?php
// The number we want to check.
$number = 42;
// Check if the remainder of the number divided by 2 is equal to 0.
if ($number % 2 == 0) {
// If it is, the number is even.
echo $number . " is an Even number.";
} else {
// If not, the number is odd.
echo $number . " is an Odd number.";
}
?>
5. Program to Print Numbers from 1 to 10 Using a for Loop
This program uses a for loop to execute a block of code repeatedly.
- Initialization (
$i = 1): The loop starts with a counter variable $i set to 1.
- Condition (
$i <= 10): The loop continues as long as $i is less than or equal to 10.
- Increment (
$i++): After each iteration, $i is increased by 1.
- The
<br> is an HTML tag for a line break, so each number appears on a new line in the browser.
<?php
// This for loop will run 10 times.
for ($i = 1; $i <= 10; $i++) {
// In each iteration, it prints the current value of $i, followed by a line break.
echo $i . "<br>";
}
?>