Basic Programs
Basic Programs
<?php
echo "Hello, World!";
?>
Explanation: This is the most basic program in any programming language. It uses the echo
statement to output the text "Hello, World!" to the browser. It's typically the first step in
learning any language to ensure the environment is set up correctly.
php
Copy
<?php
$num1 = 10;
$num2 = 5;
echo "Sum: " . ($num1 + $num2) . "<br>";
echo "Difference: " . ($num1 - $num2) . "<br>";
echo "Product: " . ($num1 * $num2) . "<br>";
echo "Quotient: " . ($num1 / $num2) . "<br>";
?>
<?php
$number = 7;
if ($number % 2 == 0) {
echo "$number is Even.";
} else {
echo "$number is Odd.";
}
?>
Explanation: The program checks if the number is even or odd. By using the modulus
operator (%), it divides the number by 2 and checks the remainder. If the remainder is 0, it
prints "Even"; otherwise, it prints "Odd."
<?php
$num1 = 10;
$num2 = 15;
$num3 = 5;
if ($num1 >= $num2 && $num1 >= $num3) {
echo "$num1 is the largest.";
} elseif ($num2 >= $num1 && $num2 >= $num3) {
echo "$num2 is the largest.";
} else {
echo "$num3 is the largest.";
}
?>
Explanation: This program compares three numbers and identifies the largest among them.
It uses conditional statements (if-else) to check each number and print the largest one.
<?php
$num = 11;
$is_prime = true;
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
$is_prime = false;
break;
}
}
if ($is_prime) {
echo "$num is a Prime number.";
} else {
echo "$num is not a Prime number.";
}
?>
Explanation: A prime number is a number greater than 1 that has no divisors other than 1
and itself. The program checks whether a number is prime by dividing it by all numbers up to
the square root of the number. If any divisor is found, it breaks the loop and concludes the
number is not prime.
6. Reverse a String
<?php
$string = "hello";
echo "Reversed string: " . strrev($string);
?>
Explanation: This program reverses the given string using PHP's built-in strrev()
function and displays the reversed string.
7. Palindrome Check
<?php
$string = "madam";
if ($string == strrev($string)) {
echo "$string is a palindrome.";
} else {
echo "$string is not a palindrome.";
}
?>
Explanation: A palindrome is a word or phrase that reads the same forwards and backwards.
The program compares the string with its reversed version using strrev() and checks if
they are identical. If they are, it confirms the string is a palindrome.
8. Factorial of a Number
<?php
$number = 5;
$factorial = 1;
for ($i = 1; $i <= $number; $i++) {
$factorial *= $i;
}
echo "Factorial of $number is $factorial.";
?>
Explanation: The program calculates the factorial of a number. The factorial of a number n
is the product of all positive integers less than or equal to n. This is done using a loop that
multiplies each integer from 1 to the number.
9. Fibonacci Series
<?php
$n = 10;
$first = 0;
$second = 1;
echo "Fibonacci Series: ";
echo "$first $second ";
for ($i = 2; $i < $n; $i++) {
$next = $first + $second;
echo "$next ";
$first = $second;
$second = $next;
}
?>
Explanation: This program generates the Fibonacci series. The Fibonacci sequence starts
with 0 and 1, and each subsequent number is the sum of the previous two. The program
generates and prints the first n numbers in the sequence.
<?php
$array = [5, 2, 8, 1, 3];
sort($array);
echo "Sorted Array: ";
print_r($array);
?>
Explanation: This program demonstrates the sorting of an array. It uses PHP's built-in
sort() function to sort the array in ascending order and then prints the sorted array using
print_r().
<?php
$array = [1, 2, 3, 4, 5];
echo "Sum of array elements: " . array_sum($array);
?>
Explanation: This program calculates the sum of all elements in an array using the
array_sum() function and prints the result.
<?php
$array = [1, 2, 3, 4, 5];
echo "Number of elements: " . count($array);
?>
Explanation: This program counts the number of elements in an array using PHP's built-in
count() function and displays the count.
<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, $name!";
}
?>
Explanation: This program demonstrates basic form handling in PHP. The user submits their
name through an HTML form, and PHP processes the form data using the $_POST array. It
then displays a greeting message with the user's name.
<?php
$count = 1;
while ($count <= 5) {
echo "Count is $count<br>";
$count++;
}
?>
Explanation: The program uses a while loop to print numbers from 1 to 5. The loop
continues as long as the condition $count <= 5 is true, incrementing $count with each
iteration.
<?php
$count = 1;
do {
echo "Count is $count<br>";
$count++;
} while ($count <= 5);
?>
Explanation: This program uses a do-while loop, which executes at least once before
checking the loop condition. It prints numbers from 1 to 5.
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count is $i<br>";
}
?>
Explanation: This program demonstrates the for loop, which is used to iterate through a
block of code a specified number of times. Here, it prints numbers from 1 to 5.
<?php
$base = 2;
$exponent = 3;
echo "Power: " . pow($base, $exponent);
?>
Explanation: This program calculates the power of a number using PHP's built-in pow()
function. The function raises the $base to the power of $exponent.
<?php
echo "Current date and time: " . date("Y-m-d H:i:s");
?>
Explanation: This program uses PHP's date() function to display the current date and
time in the specified format (Y-m-d H:i:s for year-month-day hour:minute:second).
<?php
$string = "Hello, PHP!";
echo "The length of the string is: " . strlen($string);
?>
Explanation: This program calculates the length of a given string using PHP's built-in
strlen() function, which counts the number of characters in the string.
<?php
$array = [
["John", 25],
["Anna", 30],
["Peter", 35]
];
foreach ($array as $person) {
echo $person[0] . " is " . $person[1] . " years old.<br>";
}
?>
<?php
$celsius = 25;
$fahrenheit = ($celsius * 9/5) + 32;
echo "$celsius Celsius is equal to $fahrenheit Fahrenheit.";
?>
Explanation: This program converts a given temperature from Celsius to Fahrenheit using
the formula: Fahrenheit = (Celsius * 9/5) + 32.
<?php
$fahrenheit = 77;
$celsius = ($fahrenheit - 32) * 5/9;
echo "$fahrenheit Fahrenheit is equal to $celsius Celsius.";
?>
Explanation: This program converts a given temperature from Fahrenheit to Celsius using
the formula: Celsius = (Fahrenheit - 32) * 5/9.
<?php
$number = 16;
echo "The square root of $number is " . sqrt($number);
?>
Explanation: This program calculates the square root of a number using the sqrt()
function in PHP.
<?php
$string = "Hello, PHP!";
$length = 0;
while (isset($string[$length])) {
$length++;
}
echo "The length of the string is: $length";
?>
Explanation: This program manually calculates the length of a string by iterating through
each character and counting how many characters are present.
<?php
$a = 5;
$b = 10;
$a = $a + $b;
$b = $a - $b;
$a = $a - $b;
echo "After swapping, a = $a, b = $b";
?>
Explanation: This program swaps two numbers without using a temporary variable. The
numbers are swapped using arithmetic operations (addition and subtraction).
<?php
$num = 5;
echo "Multiplication table of $num:<br>";
for ($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
?>
Explanation: This program prints the multiplication table of a number. It uses a for loop to
iterate from 1 to 10 and prints the multiplication result for each iteration.
<?php
$num1 = 56;
$num2 = 98;
while ($num1 != $num2) {
if ($num1 > $num2) {
$num1 -= $num2;
} else {
$num2 -= $num1;
}
}
echo "GCD is $num1";
?>
Explanation: This program calculates the Greatest Common Divisor (GCD) of two numbers
using the Euclidean algorithm, where the larger number is repeatedly reduced by the smaller
number until they are equal, which is the GCD.
<?php
$num1 = 12;
$num2 = 15;
$lcm = ($num1 * $num2) / gcd($num1, $num2);
echo "LCM of $num1 and $num2 is $lcm";
Explanation: This program calculates the Least Common Multiple (LCM) of two numbers
by using the formula: LCM = (num1 * num2) / GCD(num1, num2). It also uses a
helper function to compute the GCD.
<?php
$number = 12345;
$sum = 0;
while ($number > 0) {
$sum += $number % 10;
$number = (int)($number / 10);
}
echo "Sum of digits: $sum";
?>
Explanation: This program calculates the sum of digits of a number. It uses a while loop to
extract each digit of the number (by taking the modulus and integer division) and adds them
to a sum.
<?php
$start = 10;
$end = 50;
echo "Prime numbers between $start and $end are: ";
for ($i = $start; $i <= $end; $i++) {
$is_prime = true;
for ($j = 2; $j <= sqrt($i); $j++) {
if ($i % $j == 0) {
$is_prime = false;
break;
}
}
if ($is_prime && $i > 1) {
echo "$i ";
}
}
?>
Explanation: This program finds all prime numbers within a specified range. It iterates
through the range, checks if each number is prime, and then prints the prime numbers.
<?php
$operand1 = 10;
$operand2 = 5;
$operation = '+';
switch ($operation) {
case '+':
echo "Sum: " . ($operand1 + $operand2);
break;
case '-':
echo "Difference: " . ($operand1 - $operand2);
break;
case '*':
echo "Product: " . ($operand1 * $operand2);
break;
case '/':
echo "Quotient: " . ($operand1 / $operand2);
break;
default:
echo "Invalid operation";
}
?>
<?php
$string = "Hello, World!";
$vowel_count = 0;
$vowels = ['a', 'e', 'i', 'o', 'u'];
for ($i = 0; $i < strlen($string); $i++) {
if (in_array(strtolower($string[$i]), $vowels)) {
$vowel_count++;
}
}
echo "Number of vowels: $vowel_count";
?>
Explanation: This program counts the number of vowels (a, e, i, o, u) in a given string. It
iterates over each character in the string, checks if it is a vowel, and increments the counter.
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
for ($j = 1; $j <= $rows - $i; $j++) {
echo " ";
}
for ($k = 1; $k <= (2 * $i - 1); $k++) {
echo "*";
}
echo "<br>";
}
?>
Explanation: This program prints a pyramid pattern of stars. It uses nested loops to control
the number of spaces and stars in each row.
<?php
$random_number = rand(1, 100);
echo "Random number between 1 and 100: $random_number";
?>
Explanation: This program generates a random number between 1 and 100 using the
rand() function and prints it.
<?php
$string = "hello, world!";
echo strtoupper($string);
?>
Explanation: This program converts a given string to uppercase using PHP's built-in
strtoupper() function and outputs the result.
<?php
$string = "HELLO, WORLD!";
echo strtolower($string);
?>
<?php
$year = 2024;
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 ==
0)) {
echo "$year is a Leap Year.";
} else {
echo "$year is not a Leap Year.";
}
?>
Explanation: This program checks if a given year is a leap year. A leap year occurs if the
year is divisible by 4, but not by 100 unless it's also divisible by 400.
<form method="post">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username == "admin" && $password == "password") {
echo "Login Successful!";
} else {
echo "Invalid Credentials!";
}
}
?>
Explanation: This program creates a simple login form where the username is checked
against a fixed value ("admin") and the password is checked against a fixed value
("password"). If both match, it displays a success message; otherwise, it shows an error
message.
<?php
$string = "Hello World!";
echo "Without spaces: " . str_replace(' ', '', $string);
?>
Explanation: This program removes all white spaces from a string using PHP's
str_replace() function.
<?php
$person = [
"name" => "John",
"age" => 30,
"email" => "[email protected]"
];
echo "Name: " . $person["name"] . "<br>";
echo "Age: " . $person["age"] . "<br>";
echo "Email: " . $person["email"];
?>
Explanation: This program demonstrates an associative array where the keys are strings
("name", "age", "email") and the values are the corresponding data. It then prints each
key-value pair.