0% found this document useful (0 votes)
2 views

Basic Programs

The document contains a series of PHP programming examples, ranging from basic syntax to more complex operations. Each example includes a code snippet followed by an explanation of its functionality, covering topics like arithmetic operations, string manipulation, loops, and form handling. The document serves as a comprehensive guide for beginners to learn essential PHP programming concepts.

Uploaded by

noyalaugusthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Basic Programs

The document contains a series of PHP programming examples, ranging from basic syntax to more complex operations. Each example includes a code snippet followed by an explanation of its functionality, covering topics like arithmetic operations, string manipulation, loops, and form handling. The document serves as a comprehensive guide for beginners to learn essential PHP programming concepts.

Uploaded by

noyalaugusthy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

Hello World Program

<?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.

2. Simple Arithmetic Operations

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>";
?>

Explanation: This program demonstrates basic arithmetic operations such as addition,


subtraction, multiplication, and division. It stores two numbers ($num1 and $num2) and
performs operations on them, printing the results.

3. Check Even or Odd Number

<?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."

4. Find Largest of Three Numbers

<?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.

5. Check Prime Number

<?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.

10. Array Sorting

<?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().

11. Sum of Array Elements

<?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.

12. Count Elements in an Array

<?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.

13. Simple Form Handling

<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.

14. Using While Loop

<?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.

15. Using Do-While Loop

<?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.

16. Using For Loop

<?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.

17. Calculate the Power of a Number

<?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.

18. Display Date and Time

<?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).

19. String Length

<?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.

20. Multi-dimensional Array

<?php
$array = [
["John", 25],
["Anna", 30],
["Peter", 35]
];
foreach ($array as $person) {
echo $person[0] . " is " . $person[1] . " years old.<br>";
}
?>

Explanation: This program demonstrates the use of multi-dimensional arrays. It stores


multiple records (name and age) in a 2D array, then uses a foreach loop to print each
person's name and age.

21. Convert Celsius to Fahrenheit

<?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.

22. Convert Fahrenheit to Celsius

<?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.

23. Find the Square Root of a Number

<?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.

24. Find the Length of a String Without Built-in Function

<?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.

25. Swap Two Numbers Without a Temporary Variable

<?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).

26. Display Multiplication Table

<?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.

27. Find GCD of Two Numbers (Greatest Common Divisor)

<?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.

28. Find LCM of Two Numbers (Least Common Multiple)

<?php
$num1 = 12;
$num2 = 15;
$lcm = ($num1 * $num2) / gcd($num1, $num2);
echo "LCM of $num1 and $num2 is $lcm";

function gcd($a, $b) {


while ($b) {
$a %= $b;
$b ^= $a ^= $b ^= $a;
}
return $a;
}
?>

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.

29. Sum of Digits of a Number

<?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.

30. Find Prime Numbers in a Given Range

<?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.

31. Create a Simple Calculator Using Switch Case

<?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";
}
?>

Explanation: This program demonstrates a basic calculator using a switch statement. It


performs an operation (addition, subtraction, multiplication, or division) based on the
$operation variable.

32. Count Vowels in a String

<?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.

33. Print Pyramid Pattern

<?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.

34. Generate Random Number

<?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.

35. Convert String to Uppercase

<?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.

36. Convert String to Lowercase

<?php
$string = "HELLO, WORLD!";
echo strtolower($string);
?>

Explanation: This program converts a string to lowercase using the strtolower()


function in PHP.

37. Check if a Year is a Leap Year

<?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.

38. Create a Simple Login Form (Without Database)

<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.

39. Remove All White Spaces from a String

<?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.

40. Create an Associative Array

<?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.

You might also like