0% found this document useful (0 votes)
13 views43 pages

Assignment Php

The document contains a collection of PHP scripts demonstrating various programming concepts, including displaying messages, using variables, data types, string manipulation, and basic arithmetic operations. Each script is accompanied by comments explaining its functionality. The examples serve as practical exercises for learning PHP programming.

Uploaded by

hetvi08102004
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)
13 views43 pages

Assignment Php

The document contains a collection of PHP scripts demonstrating various programming concepts, including displaying messages, using variables, data types, string manipulation, and basic arithmetic operations. Each script is accompanied by comments explaining its functionality. The examples serve as practical exercises for learning PHP programming.

Uploaded by

hetvi08102004
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/ 43

1.

Write a PHP script to display "Welcome to PHP" on the web page

<?php
echo "Welcome to PHP";
?>

2. Write a PHP script to create and execute a basic PHP script with comments

<?php
/*
This is a simple PHP script
It prints a welcome message to the web page
*/
echo "Welcome to PHP";
?>

3. Write a PHP script to demonstrate the use of HTML within PHP.

<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>";
for ($i = 1; $i <= 10; $i++) {
echo "<tr>";
for ($j = 1; $j <= 10; $j++) {
echo "<td>" . ($i * $j) . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>

4. Write a PHP script to print a multiplication table using nested loops.


<?php
echo "<table border='1' cellpadding='5' cellspacing='0'>";
for ($i = 1; $i <= 10; $i++) {
echo "<tr>";
for ($j = 1; $j <= 10; $j++) {
echo "<td>" . ($i * $j) . "</td>";
}
echo "</tr>";
}
echo "</table>";
?>

5. Write a PHP script to demonstrate the use of PHP tags inside an HTML file.
<!DOCTYPE html>
<html>
<head>
<title>PHP Tags in HTML</title>
</head>
<body>
<h1><?php echo "Hello from PHP inside HTML!"; ?></h1>
</body>
</html>

6. Write a PHP script to include a file in another PHP file.


<?php
include 'included_file.php';
echo "File included successfully.";
?>

7. Write a PHP script to display the current date and time.


<?php
echo "Current Date and Time: " . date('Y-m-d H:i:s');
?>

8. Write a PHP script to demonstrate the use of single and double quotes in strings.

<?php
$single = 'This is a string with single quotes';
$double = "This is a string with double quotes";
echo $single . "<br>";
echo $double;
?>

9. Write a PHP script to display server information using phpinfo().

<?php
phpinfo();
?>

10. Write a PHP script to write a simple hello world program using PHP.

<?php
echo "Hello, World!";
?>

2. Variables
1. Write a PHP script to define and display the value of a variable.

<?php
$variable = "This is a PHP variable";
echo $variable;
?>

2. Write a PHP script to demonstrate the scope of a variable (local, global).

<?php
$globalVar = "I am a global variable";
function testScope() {
$localVar = "I am a local variable";
global $globalVar;
echo $localVar . "<br>";
echo $globalVar;
}
testScope();
?>

3. Write a PHP script to swap two numbers using a temporary variable.

<?php
$a = 5;
$b = 10;
echo "Before swapping: a = $a, b = $b<br>";
$temp = $a;
$a = $b;
$b = $temp;
echo "After swapping: a = $a, b = $b";
?>

4. Write a PHP script to store and display a string in a variable.

<?php
$string = "Hello, this is a PHP string!";
echo $string;
?>

5. Write a PHP script to calculate the area of a rectangle using variables.

<?php
$length = 10;
$width = 5;
$area = $length * $width;
echo "The area of the rectangle is: $area";
?>

6. Write a PHP script to store a user’s name and display it.

<?php
$name = "John Doe";
echo "User's name is: $name";
?>

7. Write a PHP script to find the sum of two numbers using variables.

<?php
$num1 = 10;
$num2 = 20;
$sum = $num1 + $num2;
echo "The sum of $num1 and $num2 is: $sum";
?>

8. Write a PHP script to assign multiple values to variables and display them.

<?php
$name = "John";
$age = 25;
$city = "New York";
echo "Name: $name<br>Age: $age<br>City: $city";
?>

9. Write a PHP script to display the type of a variable

<?php
$var = 10.5;
echo "The type of variable is: " . gettype($var);
?>

10. Write a PHP script to demonstrate variable interpolation in strings.

<?php
$name = "John";
$age = 25;
echo "My name is $name and I am $age years old.";
?>

3. Data Types
1. Write a PHP script to demonstrate the integer data type.

<?php
// Declaring integer variables
$int1 = 42; // Positive integer
$int2 = -10; // Negative integer
$int3 = 0x1A; // Hexadecimal (26 in decimal)
$int4 = 0123; // Octal (83 in decimal)
$int5 = 0b1010; // Binary (10 in decimal)
// Displaying the integer values
echo "Integer 1: $int1 <br>";
echo "Integer 2: $int2 <br>";
echo "Integer 3 (Hex 0x1A): $int3 <br>";
echo "Integer 4 (Octal 0123): $int4 <br>";
echo "Integer 5 (Binary 0b1010): $int5 <br>";
// Checking the data type
var_dump($int1);
var_dump($int2);
var_dump($int3);
var_dump($int4);
var_dump($int5);
?>

2. Write a PHP script to demonstrate the float data type.

<?php
// Declaring float variables
$float1 = 3.14; // Standard float (Pi approximation)
$float2 = -2.5; // Negative float
$float3 = 1.2e3; // Scientific notation (1.2 × 10^3 = 1200)
$float4 = 7E-2; // Scientific notation (7 × 10^-2 = 0.07)

// Displaying the float values


echo "Float 1: $float1 <br>";
echo "Float 2: $float2 <br>";
echo "Float 3 (Scientific 1.2e3): $float3 <br>";
echo "Float 4 (Scientific 7E-2): $float4 <br>";

// Checking the data type


var_dump($float1);
var_dump($float2);
var_dump($float3);
var_dump($float4);
?>

3. Write a PHP script to demonstrate string concatenation

<?php

$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;

echo "Full Name: " . $fullName;

?>

4. Write a PHP script to demonstrate boolean data types

<?php

$isTrue = true;
$isFalse = false;

echo "Value of isTrue: " . ($isTrue ? 'True' : 'False') . "<br>";


echo "Value of isFalse: " . ($isFalse ? 'True' : 'False');

?>

5. Write a PHP script to display null data type behavior in PHP


<?php

$nullVar = null;

echo "Value of nullVar: ";


var_dump($nullVar);

?>

6. Write a PHP script to convert a float to an integer.

<?php

$floatNum = 10.75;
$intNum = (int) $floatNum;

echo "Float value: $floatNum<br>Converted Integer value: $intNum";

?>

7. Write a PHP script to check if a variable is of a specific type

<?php

$var = 100.5;

if (is_int($var)) {
echo "The variable is an integer.";
} elseif (is_float($var)) {
echo "The variable is a float.";
} elseif (is_string($var)) {
echo "The variable is a string.";
} elseif (is_bool($var)) {
echo "The variable is a boolean.";
} elseif (is_null($var)) {
echo "The variable is null.";
} else {
echo "The variable type is unknown.";
}

?>

8. Write a PHP script to display the type of multiple variables.

<?php

$var1 = 42;
$var2 = 3.14;
$var3 = "Hello, PHP!";
$var4 = true;
$var5 = null;
echo "Type of var1: " . gettype($var1) . "<br>";
echo "Type of var2: " . gettype($var2) . "<br>";
echo "Type of var3: " . gettype($var3) . "<br>";
echo "Type of var4: " . gettype($var4) . "<br>";
echo "Type of var5: " . gettype($var5) . "<br>";

?>

9. Write a PHP script to demonstrate type juggling in PHP

<?php

$var1 = "10" + 5; // String "10" is converted to an integer and added to 5


$var2 = "20 apples" + 10; // Numeric part of string is used, "20" becomes 20 and added to
10
$var3 = "5.5" * 2; // String "5.5" is converted to float and multiplied by 2
$var4 = true + 1; // Boolean true is converted to 1 and added to 1

echo "Result of '10' + 5: $var1 (Type: " . gettype($var1) . ")<br>";


echo "Result of '20 apples' + 10: $var2 (Type: " . gettype($var2) . ")<br>";
echo "Result of '5.5' * 2: $var3 (Type: " . gettype($var3) . ")<br>";
echo "Result of true + 1: $var4 (Type: " . gettype($var4) . ")<br>";

?>

10. Write a PHP script to add and multiply numbers of different data types.

<?php

$var1 = "10" + 5; // String "10" is converted to an integer and added to 5


$var2 = "20 apples" + 10; // Numeric part of string is used, "20" becomes 20 and added to
10
$var3 = "5.5" * 2; // String "5.5" is converted to float and multiplied by 2
$var4 = true + 1; // Boolean true is converted to 1 and added to 1

echo "Result of '10' + 5: $var1 (Type: " . gettype($var1) . ")<br>";


echo "Result of '20 apples' + 10: $var2 (Type: " . gettype($var2) . ")<br>";
echo "Result of '5.5' * 2: $var3 (Type: " . gettype($var3) . ")<br>";
echo "Result of true + 1: $var4 (Type: " . gettype($var4) . ")<br>";

?>

4. Strings
1. Write a PHP script to count the number of characters in a string

<?php
$string = "Hello, PHP!";
$length = strlen($string);

echo "The number of characters in the string is: $length";

?>

2. Write a PHP script to reverse a string.

<?php

$string = "Hello, PHP!";


$reversed = strrev($string);

echo "Reversed string: $reversed";

?>

3. Write a PHP script to convert a string to uppercase.

<?php

$string = "Hello, PHP!";


$uppercase = strtoupper($string);

echo "Uppercase string: $uppercase";

?>

4. Write a PHP script to replace a substring in a string

<?php

$string = "Hello, PHP! Welcome to PHP programming.";


$replaced = str_replace("PHP", "World", $string);

echo "Modified string: $replaced";

?>

5. Write a PHP script to extract a substring from a string.

<?php

$string = "Hello, PHP! Welcome to PHP programming.";


$substring = substr($string, 7, 3);

echo "Extracted substring: $substring";


?>

6. Write a PHP script to find the position of a substring in a string.

<?php

$string = "Hello, PHP! Welcome to PHP programming.";


$position = strpos($string, "PHP");

echo "Position of 'PHP' in the string: $position";

?>

7. Write a PHP script to split a string by a delimiter

<?php

$string = "Apple, Banana, Cherry, Mango";


$array = explode(", ", $string);

echo "Splitted string into array elements:<br>";


print_r($array);

?>

8. Write a PHP script to trim leading and trailing whitespaces in a string.

<?php
// Define a string with leading and trailing whitespaces
$string = " Hello, World! ";

// Trim the whitespaces


$trimmedString = trim($string);

// Display the original and trimmed strings


echo "Original String: '" . $string . "'\n";
echo "Trimmed String: '" . $trimmedString . "'\n";
?>

9. Write a PHP script to compare two strings.

<?php
// Define two strings
$string1 = "Hello, World!";
$string2 = "Hello, PHP!";

// Compare the strings


if ($string1 === $string2) {
echo "The strings are identical.";
} else {
echo "The strings are different.";
}
?>

10. Write a PHP script to repeat a string multiple times.

<?php
// Define a string
$string = "Hello, World! ";

// Define the number of times to repeat


$repeatCount = 3;

// Repeat the string


$repeatedString = str_repeat($string, $repeatCount);

// Display the repeated string


echo $repeatedString;
?>

5. Numbers
1. Write a PHP script to perform basic arithmetic operations.

<?php
// Define two numbers
$num1 = 10;
$num2 = 5;

// Perform arithmetic operations


$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;
$quotient = $num1 / $num2;
$modulus = $num1 % $num2;

// Display the results


echo "Sum: $sum\n";
echo "Difference: $difference\n";
echo "Product: $product\n";
echo "Quotient: $quotient\n";
echo "Modulus: $modulus\n";
?>

2. Write a PHP script to calculate the square root of a number.

<?php
// Define a number
$number = 25;
// Calculate the square root
$squareRoot = sqrt($number);

// Display the result


echo "The square root of $number is $squareRoot\n";
?>

3. Write a PHP script to generate a random numbe

<?php
// Generate a random number between 1 and 100
$randomNumber = rand(1, 100);

// Display the random number


echo "Random Number: $randomNumber\n";
?>

4. Write a PHP script to find the largest and smallest number in an array.

<?php
// Define an array of numbers
$numbers = [10, 25, 5, 40, 15];

// Find the largest and smallest numbers


$largest = max($numbers);
$smallest = min($numbers);

// Display the results


echo "Largest Number: $largest\n";
echo "Smallest Number: $smallest\n";
?>

5. Write a PHP script to round a float number to the nearest integer.

<?php
// Define a float number
$number = 7.6;

// Round the number to the nearest integer


$roundedNumber = round($number);

// Display the result


echo "The rounded number is: $roundedNumber\n";
?>

6. Write a PHP script to calculate the power of a number


<?php
// Define the base and exponent
$base = 3;
$exponent = 4;

// Calculate the power


$result = pow($base, $exponent);

// Display the result


echo "$base raised to the power of $exponent is: $result\n";
?>

7. Write a PHP script to convert a string to a number.

<?php
// Define a string containing a number
$stringNumber = "123.45";

// Convert the string to a number


$integerValue = (int)$stringNumber;
$floatValue = (float)$stringNumber;

// Display the results


echo "Integer Value: $integerValue\n";
echo "Float Value: $floatValue\n";
?>

8. Write a PHP script to find the absolute value of a number.

<?php
// Define a number
$number = -25;

// Get the absolute value


$absoluteValue = abs($number);

// Display the result


echo "The absolute value of $number is: $absoluteValue\n";
?>

9. Write a PHP script to calculate the factorial of a number.

<?php
// Function to calculate factorial
function factorial($num) {
if ($num <= 1) {
return 1;
}
return $num * factorial($num - 1);
}

// Define a number
$number = 5;

// Calculate factorial
$result = factorial($number);

// Display the result


echo "The factorial of $number is: $result\n";
?>

10. Write a PHP script to determine whether a number is even or odd.

<?php
// Function to check if a number is even or odd
function checkEvenOdd($num) {
return ($num % 2 == 0) ? "even" : "odd";
}

// Define a number
$number = 7;

// Determine if the number is even or odd


$result = checkEvenOdd($number);

// Display the result


echo "The number $number is: $result\n";
?>

6. Constants
1. Write a PHP script to define and display a constant.

<?php
// Define a constant
define("SITE_NAME", "MyWebsite");

// Display the constant


echo "The site name is: " . SITE_NAME . "\n";
?>

2. Write a PHP script to check if a constant is defined

<?php
// Define a constant
define("SITE_NAME", "MyWebsite");

// Check if the constant is defined


if (defined("SITE_NAME")) {
echo "The constant SITE_NAME is defined with value: " . SITE_NAME .
"\n";
} else {
echo "The constant SITE_NAME is not defined.\n";
}
?>

3. Write a PHP script to define multiple constants and display them

<?php
// Define multiple constants
define("SITE_NAME", "MyWebsite");
define("SITE_URL", "https://www.mywebsite.com");
define("ADMIN_EMAIL", "[email protected]");

// Display the constants


echo "Site Name: " . SITE_NAME . "\n";
echo "Site URL: " . SITE_URL . "\n";
echo "Admin Email: " . ADMIN_EMAIL . "\n";
?>

4. Write a PHP script to define case-insensitive constants.

<?php
// Define case-insensitive constant (Note: This feature is deprecated in
PHP 7.3 and removed in PHP 8.0)
define("SITE_NAME", "MyWebsite", true);

// Display the constant


echo "Site Name: " . SITE_NAME . "\n";
echo "Site Name (lowercase reference): " . site_name . "\n";
?>

5. Write a PHP script to use constants within a mathematical calculation.

<?php
// Define constants
define("PI", 3.14159);
define("RADIUS", 5);

// Calculate the area of a circle


$area = PI * pow(RADIUS, 2);

// Display the result


echo "The area of a circle with radius " . RADIUS . " is: " . $area . "\n";
?>

6. Write a PHP script to display the value of PHP predefined constants.

<?php
// Define constants
define("PI", 3.14159);
define("RADIUS", 5);

// Calculate the area of a circle


$area = PI * pow(RADIUS, 2);

// Display the result


echo "The area of a circle with radius " . RADIUS . " is: " . $area . "\n";
?>

7. Write a PHP script to use constants inside a function.

<?php
// Define a constant
define("GREETING", "Welcome to MyWebsite!");

// Function to display the constant


function displayGreeting() {
echo GREETING . "\n";
}

// Call the function


displayGreeting();
?>

8. Write a PHP script to demonstrate the immutability of constants.

<?php
// Define a constant
define("SITE_NAME", "MyWebsite");

// Attempt to modify the constant (this will not work)


// SITE_NAME = "NewWebsite"; // Uncommenting this line will cause an
error

// Display the constant


echo "Site Name: " . SITE_NAME . "\n";

// Demonstrating immutability
echo "Constants cannot be changed after they are defined.";
?>

9. Write a PHP script to define constants using the const keyword.

<?php
// Define constants using the const keyword
const SITE_NAME = "MyWebsite";
const SITE_URL = "https://www.mywebsite.com";

// Display the constants


echo "Site Name: " . SITE_NAME . "\n";
echo "Site URL: " . SITE_URL . "\n";
?>

10. Write a PHP script to demonstrate constants within a class.

<?php
// Define a class with constants
class Website {
const SITE_NAME = "MyWebsite";
const SITE_URL = "https://www.mywebsite.com";

// Method to display constants


public static function displayInfo() {
echo "Site Name: " . self::SITE_NAME . "\n";
echo "Site URL: " . self::SITE_URL . "\n";
}
}

// Access constants from the class


Website::displayInfo();
?>

7. Operators
1. Write a PHP script to demonstrate arithmetic operators.

<?php
// Define two numbers
$num1 = 10;
$num2 = 5;

// Perform arithmetic operations


echo "Addition: " . ($num1 + $num2) . "\n";
echo "Subtraction: " . ($num1 - $num2) . "\n";
echo "Multiplication: " . ($num1 * $num2) . "\n";
echo "Division: " . ($num1 / $num2) . "\n";
echo "Modulus: " . ($num1 % $num2) . "\n";
echo "Exponentiation: " . ($num1 ** $num2) . "\n";
?>

2. Write a PHP script to demonstrate comparison operators.

<?php
// Define two numbers
$num1 = 10;
$num2 = 5;

// Perform comparison operations


echo "Equal: " . ($num1 == $num2 ? 'true' : 'false') . "\n";

echo "Identical: " . ($num1 === $num2 ? 'true' : 'false') . "\n";

echo "Not Equal: " . ($num1 != $num2 ? 'true' : 'false') . "\n";

echo "Not Identical: " . ($num1 !== $num2 ? 'true' : 'false') . "\n";

echo "Greater Than: " . ($num1 > $num2 ? 'true' : 'false') . "\n";

echo "Less Than: " . ($num1 < $num2 ? 'true' : 'false') . "\n";

echo "Greater Than or Equal To: " . ($num1 >= $num2 ? 'true' :
'false') . "\n";

echo "Less Than or Equal To: " . ($num1 <= $num2 ? 'true' : 'false') .
"\n";
?>

3. Write a PHP script to demonstrate logical operators.

<?php
// Define two boolean values
$bool1 = true;
$bool2 = false;

// Perform logical operations


echo "AND Operator: " . ($bool1 && $bool2 ? 'true' : 'false') . "\n";
echo "OR Operator: " . ($bool1 || $bool2 ? 'true' : 'false') . "\n";
echo "NOT Operator (!bool1): " . (!$bool1 ? 'true' : 'false') . "\n";
echo "XOR Operator: " . ($bool1 xor $bool2 ? 'true' : 'false') . "\n";
?>

4. Write a PHP script to demonstrate bitwise operators.

<?php
// Define two numbers
$num1 = 6; // 110 in binary
$num2 = 3; // 011 in binary

// Perform bitwise operations


echo "Bitwise AND: " . ($num1 & $num2) . "\n";
echo "Bitwise OR: " . ($num1 | $num2) . "\n";
echo "Bitwise XOR: " . ($num1 ^ $num2) . "\n";
echo "Bitwise NOT (~num1): " . (~$num1) . "\n";
echo "Left Shift (num1 << 1): " . ($num1 << 1) . "\n";
echo "Right Shift (num1 >> 1): " . ($num1 >> 1) . "\n";
?>

5. Write a PHP script to demonstrate the ternary operator

<?php
// Define a number
$number = 10;

// Use the ternary operator to check if the number is even or odd


$result = ($number % 2 == 0) ? "Even" : "Odd";

// Display the result


echo "The number $number is: $result\n";
?>

6. Write a PHP script to demonstrate increment and decrement operators.

<?php
// Define a number
$number = 10;

// Demonstrate increment and decrement operators


echo "Original Number: " . $number . "\n";
echo "Post-Increment: " . $number++ . " (After increment:
$number)\n";
echo "Pre-Increment: " . ++$number . "\n";
echo "Post-Decrement: " . $number-- . " (After decrement:
$number)\n";
echo "Pre-Decrement: " . --$number . "\n";
?>

7. Write a PHP script to demonstrate string concatenation operators.


<?php
// Define two strings
$str1 = "Hello";
$str2 = "World";
// Concatenate strings using the concatenation operator (.)
$concatenatedString = $str1 . " " . $str2;

echo "Concatenated String: " . $concatenatedString . "\n";

// Concatenation assignment operator (.=)


$str1 .= " " . $str2;
echo "Concatenation Assignment: " . $str1 . "\n";
?>

8. Write a PHP script to demonstrate assignment operators.

<?php
// Define a variable
$number = 10;

echo "Initial Value: " . $number . "\n";

// Assignment operators
$number += 5;
echo "After += 5: " . $number . "\n";

$number -= 3;
echo "After -= 3: " . $number . "\n";

$number *= 2;
echo "After *= 2: " . $number . "\n";

$number /= 4;
echo "After /= 4: " . $number . "\n";

$number %= 3;
echo "After %= 3: " . $number . "\n";

$number **= 2;
echo "After **= 2: " . $number . "\n";
?>

9. Write a PHP script to calculate compound interest using operators.

<?php
// Function to calculate compound interest
function calculateCompoundInterest($principal, $rate, $time, $n) {
$amount = $principal * pow((1 + $rate / ($n * 100)), $n * $time);
return $amount - $principal;
}

// Define variables
$principal = 1000; // Initial amount
$rate = 5; // Annual interest rate in percentage
$time = 3; // Time in years
$n = 4; // Number of times interest is compounded per year

// Calculate compound interest


$compoundInterest = calculateCompoundInterest($principal, $rate, $time,
$n);

// Display the result


echo "Compound Interest: " . number_format($compoundInterest, 2) . "\
n";
?>

8. Loop Structures
1. Write a PHP script to display numbers from 1 to 10 using a for loop.

<?php
// Display numbers from 1 to 10 using a for loop
for ($i = 1; $i <= 10; $i++) {
echo $i . "\n";
}
?>

2. Write a PHP script to display the Fibonacci series using a while loop.

<?php
// Display Fibonacci series using a while loop
$limit = 10; // Number of terms
$first = 0;
$second = 1;
$count = 0;

echo "Fibonacci Series:\n";


while ($count < $limit) {
echo $first . " ";
$next = $first + $second;
$first = $second;
$second = $next;
$count++;
}
echo "\n";
?>

3. Write a PHP script to display a multiplication table using nested


loops.

<?php
// Display a multiplication table using nested loops
$size = 10; // Table size
echo "Multiplication Table:\n";
for ($i = 1; $i <= $size; $i++) {
for ($j = 1; $j <= $size; $j++) {
echo str_pad($i * $j, 4, " ", STR_PAD_LEFT);
}
echo "\n";
}
?>

4. Write a PHP script to find the sum of the first 10 natural numbers
using a do-while loop.

<?php
// Find the sum of the first 10 natural numbers using a do-while
loop
$sum = 0;
$number = 1;

do {
$sum += $number;
$number++;
} while ($number <= 10);

echo "Sum of the first 10 natural numbers: " . $sum . "\n";


?>

5. Write a PHP script to display an array's elements using a foreach


loop.

<?php
// Define an array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Display array elements using a foreach loop


echo "Array Elements:\n";
foreach ($numbers as $number) {
echo $number . " ";
}
echo "\n";
?>

6. Write a PHP script to check whether a number is prime using a loop.

<?php
// Function to check if a number is prime
function isPrime($num) {
if ($num < 2) {
return false;
}
for ($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
return false;
}
}
return true;
}

// Define a number to check


$number = 29;

// Check if the number is prime


echo $number . (isPrime($number) ? " is a prime number." : " is
not a prime number.") . "\n";
?>

7. Write a PHP script to count the number of even numbers in an array


using a loop.

<?php
// Define an array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Count the number of even numbers


$evenCount = 0;
foreach ($numbers as $number) {
if ($number % 2 == 0) {
$evenCount++;
}
}

echo "Number of even numbers: " . $evenCount . "\n";


?>

8. Write a PHP script to calculate the factorial of a number using a loop.

<?php
// Function to calculate the factorial of a number
function factorial($num) {
$factorial = 1;
for ($i = 1; $i <= $num; $i++) {
$factorial *= $i;
}
return $factorial;
}
// Define a number
$number = 5;

// Calculate and display the factorial


echo "Factorial of $number is: " . factorial($number) . "\n";
?>

9. Write a PHP script to display numbers from 1 to 50, skipping


multiples of 5.

<?php
// Display numbers from 1 to 50, skipping multiples of 5
for ($i = 1; $i <= 50; $i++) {
if ($i % 5 == 0) {
continue;
}
echo $i . " ";
}
echo "\n";
?>

10. Write a PHP script to reverse the digits of a number using a loop.

<?php
// Function to reverse the digits of a number
function reverseNumber($num) {
$reversed = 0;
while ($num > 0) {
$reversed = ($reversed * 10) + ($num % 10);
$num = (int)($num / 10);
}
return $reversed;
}

// Define a number
$number = 12345;

// Reverse and display the number


echo "Reversed number: " . reverseNumber($number) . "\n";
?>

9. Functions
1. Write a PHP script to create and call a function to print
"Hello, PHP".

<?php
// Define a function to print 'Hello, PHP'
function sayHello() {
echo 'Hello, PHP';
}

// Call the function


sayHello();
?>

2. Write a PHP script to calculate the factorial of a number


using a function

<?php
// Function to calculate the factorial of a number
function factorial($num) {
$factorial = 1;
for ($i = 1; $i <= $num; $i++) {
$factorial *= $i;
}
return $factorial;
}

// Define a number
$number = 5;

// Calculate and display the factorial


echo "Factorial of $number is: " . factorial($number) . "\n";
?>

3. Write a PHP script to demonstrate the use of default


parameters in a function

<?php
// Function with default parameters
function greet($name = "Guest", $message = "Welcome to
PHP!") {
echo "Hello, $name! $message\n";
}

// Call the function without passing any arguments (defaults


will be used)
greet();

// Call the function with custom arguments


greet("John", "Have a great day!");
?>
4. Write a PHP script to pass an array to a function and display
its elements.

<?php
// Function to display elements of an array
function displayArray($array) {
foreach ($array as $element) {
echo $element . "\n";
}
}

// Define an array
$numbers = [1, 2, 3, 4, 5];

// Call the function and pass the array to it


displayArray($numbers);
?>

5. Write a PHP script to return the largest number from an array


using a function.

<?php
// Function to find the largest number in an array
function findLargestNumber($array) {
// Use the max() function to get the largest number
return max($array);
}

// Define an array
$numbers = [3, 7, 2, 9, 5, 12, 8];

// Call the function and get the largest number


$largestNumber = findLargestNumber($numbers);

// Display the largest number


echo "The largest number in the array is: $largestNumber\
n";
?>

6. Write a PHP script to demonstrate the concept of recursive


functions.

<?php
// Recursive function to calculate factorial
function factorial($num) {
// Base case: if the number is 1 or less, return 1
if ($num <= 1) {
return 1;
} else {
// Recursive case: multiply the current number with the
factorial of the previous number
return $num * factorial($num - 1);
}
}

// Define a number
$number = 5;

// Calculate and display the factorial using recursion


echo "Factorial of $number is: " . factorial($number) . "\n";
?>
7. Write a PHP script to demonstrate call-by-value and call-by-
reference in functions.

<?php
// Call-by-value function
function callByValue($num) {
// Modify the parameter inside the function
$num = $num * 2;
echo "Inside callByValue function: $num\n";
}

// Call-by-reference function
function callByReference(&$num) {
// Modify the parameter inside the function
$num = $num * 2;
echo "Inside callByReference function: $num\n";
}

// Demonstrating Call-by-Value
$number1 = 5;
echo "Before callByValue: $number1\n";
callByValue($number1); // This won't modify $number1
outside the function
echo "After callByValue: $number1\n\n";

// Demonstrating Call-by-Reference
$number2 = 5;
echo "Before callByReference: $number2\n";
callByReference($number2); // This will modify $number2
outside the function
echo "After callByReference: $number2\n";
?>

8. Write a PHP script to calculate the area of a circle using a


function.
<?php
// Function to calculate the area of a circle
function calculateArea($radius) {
// Formula for area of a circle: A = π * r^2
return pi() * pow($radius, 2);
}

// Define the radius


$radius = 5;

// Calculate and display the area of the circle


$area = calculateArea($radius);
echo "The area of a circle with radius $radius is: " . $area . "\n";
?>
9. Write a PHP script to demonstrate anonymous functions.

<?php
// Simple anonymous function
$greet = function($name) {
return "Hello, $name!";
};

// Call the function


echo $greet("John") . "\n";

// Passing an anonymous function to another function


function execute($callback) {
echo $callback("PHP") . "\n";
}

execute(function($name) {
return "Welcome to $name!";
});
?>

10. Arrays
1. Write a PHP script to create and display an indexed array.

<?php
// Create an indexed array
$fruits = ["Apple", "Banana", "Orange", "Grapes"];

// Display the elements of the indexed array


echo "Fruits in the array: \n";
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>
2. Write a PHP script to create and display an associative array.

<?php
// Create an associative array
$person = [
"name" => "John",
"age" => 25,
"city" => "New York"
];

// Display the elements of the associative array


echo "Person details: \n";
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
?>

3. Write a PHP script to merge two arrays.

<?php
// Create two arrays
$array1 = ["Apple", "Banana", "Orange"];
$array2 = ["Grapes", "Mango", "Pineapple"];

// Merge the arrays using array_merge() function


$mergedArray = array_merge($array1, $array2);

// Display the merged array


echo "Merged Array: \n";
foreach ($mergedArray as $fruit) {
echo $fruit . "\n";
}
?>

4. Write a PHP script to sort an array in ascending and


descending order.

<?php
// Create an array
$numbers = [5, 3, 8, 1, 2, 7];

// Sort the array in ascending order


sort($numbers);
echo "Array sorted in ascending order: \n";
foreach ($numbers as $number) {
echo $number . "\n";
}

// Sort the array in descending order


rsort($numbers);
echo "\nArray sorted in descending order: \n";
foreach ($numbers as $number) {
echo $number . "\n";
}
?>

5. Write a PHP script to find the length of an array.

<?php
// Define an array
$array = array(1, 2, 3, 4, 5);

// Use the count() function to find the length of the array


$length = count($array);

// Output the length


echo "The length of the array is: " . $length;
?>

6. Write a PHP script to search for an element in an array.

<?php
// Define an array
$array = array(10, 20, 30, 40, 50);

// Element to search for


$element = 30;

// Use the in_array() function to check if the element exists in


the array
if (in_array($element, $array)) {
echo "Element $element found in the array.";
} else {
echo "Element $element not found in the array.";
}
?>

7. Write a PHP script to demonstrate multidimensional


arrays.

<?php
// Define a multidimensional array
$students = array(
// Student 1
array(
"name" => "John",
"age" => 20,
"subjects" => array("Math", "Science", "History")
),
// Student 2
array(
"name" => "Emma",
"age" => 22,
"subjects" => array("English", "Math", "Art")
),
// Student 3
array(
"name" => "Sam",
"age" => 21,
"subjects" => array("Geography", "Physics", "Chemistry")
)
);

// Access and display information from the multidimensional


array
echo "Student 1 Name: " . $students[0]['name'] . "<br>";
echo "Student 1 Age: " . $students[0]['age'] . "<br>";
echo "Student 1 Subjects: " . implode(", ", $students[0]
['subjects']) . "<br><br>";

echo "Student 2 Name: " . $students[1]['name'] . "<br>";


echo "Student 2 Age: " . $students[1]['age'] . "<br>";
echo "Student 2 Subjects: " . implode(", ", $students[1]
['subjects']) . "<br><br>";

echo "Student 3 Name: " . $students[2]['name'] . "<br>";


echo "Student 3 Age: " . $students[2]['age'] . "<br>";
echo "Student 3 Subjects: " . implode(", ", $students[2]
['subjects']) . "<br>";
?>

8. Write a PHP script to remove duplicate values from an


array.

<?php
// Define an array with duplicate values
$array = array(1, 2, 3, 4, 5, 2, 3, 6, 4);

// Use array_unique() to remove duplicate values


$uniqueArray = array_unique($array);

// Output the array with duplicates removed


echo "Array after removing duplicates: ";
print_r($uniqueArray);
?>

9. Write a PHP script to find the sum of elements in an


array.

<?php
// Define an array of numbers
$array = array(10, 20, 30, 40, 50);
// Use the array_sum() function to find the sum of elements
$sum = array_sum($array);

// Output the sum


echo "The sum of the array elements is: " . $sum;
?>

10. Write a PHP script to display only unique elements from


an array.

<?php
// Define an array with some duplicate values
$array = array(1, 2, 2, 3, 4, 5, 5, 6);

// Count the occurrences of each element


$counts = array_count_values($array);

// Filter the array to only include elements that appear once


$uniqueElements = array_filter($counts, function($count) {
return $count === 1;
});

// Get the keys of the filtered array, which are the unique
elements
$uniqueElements = array_keys($uniqueElements);

// Output the unique elements


echo "The unique elements in the array are: ";
print_r($uniqueElements);
?>

11.Superglobals
1. Write a PHP script to demonstrate the use of $_GET
to send data

P1.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GET Method Example</title>
</head>
<body>

<h1>Send Data Using GET Method</h1>


<!-- Form that sends data to process.php using GET
method -->
<form action="process.php" method="get">
<label for="name">Enter your name: </label>
<input type="text" name="name" id="name"
required>
<input type="submit" value="Submit">
</form>

</body>
</html>

(process.php)

<?php
// Check if the 'name' parameter exists in the URL
if (isset($_GET['name'])) {
// Get the name sent via GET method
$name = $_GET['name'];

// Display the name


echo "Hello, " . htmlspecialchars($name) . "!
Welcome to our website.";
} else {
echo "No data was sent!";
}
?>

2. Write a PHP script to demonstrate the use of


$_POST to handle form data.

(form.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>POST Method Example</title>
</head>
<body>

<h1>Send Data Using POST Method</h1>

<!-- Form that sends data to process.php using


POST method -->
<form action="process.php" method="post">
<label for="name">Enter your name: </label>
<input type="text" name="name" id="name"
required><br><br>

<label for="email">Enter your email: </label>


<input type="email" name="email" id="email"
required><br><br>

<input type="submit" value="Submit">


</form>

</body>
</html>

(process.php)

<?php
// Check if the form data exists
if (isset($_POST['name']) && isset($_POST['email'])) {
// Get the name and email sent via POST method
$name = $_POST['name'];
$email = $_POST['email'];

// Display the submitted data


echo "Hello, " . htmlspecialchars($name) . "!<br>";
echo "Your email address is: " .
htmlspecialchars($email);
} else {
echo "No data was submitted!";
}
?>

3. Write a PHP script to demonstrate the use of


$_REQUEST.

(form.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$_REQUEST Example</title>
</head>
<body>

<h1>Submit Data Using GET or POST</h1>


<!-- Form that sends data to process.php using
POST method -->
<form action="process.php" method="post">
<label for="name">Enter your name: </label>
<input type="text" name="name" id="name"
required><br><br>

<label for="email">Enter your email: </label>


<input type="email" name="email" id="email"
required><br><br>

<input type="submit" value="Submit">


</form>

<!-- Form that sends data to process.php using GET


method -->
<h2>Or send data via GET</h2>
<form action="process.php" method="get">
<label for="name">Enter your name: </label>
<input type="text" name="name" id="name"
required><br><br>

<label for="email">Enter your email: </label>


<input type="email" name="email" id="email"
required><br><br>

<input type="submit" value="Submit">


</form>

</body>
</html>

(process.php)

<?php
// Check if 'name' and 'email' exist in the $_REQUEST
array
if (isset($_REQUEST['name']) &&
isset($_REQUEST['email'])) {
// Get the name and email from the $_REQUEST
array
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
// Display the submitted data
echo "Hello, " . htmlspecialchars($name) . "!<br>";
echo "Your email address is: " .
htmlspecialchars($email);
} else {
echo "No data was submitted!";
}
?>

4. Write a PHP script to demonstrate the use of


$_SESSION.

(set_session.php)

<?php
// Start the session
session_start();

// Set session variables


$_SESSION['username'] = 'JohnDoe';
$_SESSION['email'] = '[email protected]';

// Output a message
echo "Session variables are set.<br>";
echo "Username: " . $_SESSION['username'] . "<br>";
echo "Email: " . $_SESSION['email'] . "<br>";
echo "<a href='get_session.php'>Go to next page to
see session data</a>";
?>

(get_session.php)

<?php
// Start the session
session_start();

// Check if session variables are set and display them


if (isset($_SESSION['username']) &&
isset($_SESSION['email'])) {
echo "Hello, " . $_SESSION['username'] . "!<br>";
echo "Your email address is: " .
$_SESSION['email'] . "<br>";
} else {
echo "Session variables are not set!<br>";
}
echo "<br><a href='destroy_session.php'>Click here
to destroy the session</a>";
?>

(destroy_session.php)

<?php
// Start the session
session_start();

// Destroy all session variables


session_unset();

// Destroy the session


session_destroy();

echo "Session has been destroyed. <a


href='set_session.php'>Go back to set session</a>";
?>

5. Write a PHP script to demonstrate the use of


$_COOKIE.

(set_cookie.php)

<?php
// Set a cookie that expires in 1 hour (3600 seconds)
setcookie("user", "JohnDoe", time() + 3600, "/");

echo "Cookie has been set!<br>";


echo "Go to <a href='get_cookie.php'>view the
cookie</a>.";
?>

(get_cookie.php)

<?php
// Check if the cookie exists
if(isset($_COOKIE['user'])) {
echo "Hello, " . $_COOKIE['user'] . "!<br>";
} else {
echo "Cookie 'user' is not set!<br>";
}
echo "<a href='destroy_cookie.php'>Click here to
delete the cookie</a>";
?>

(destroy_cookie.php)

<?php
// Delete the cookie by setting the expiration date in
the past
setcookie("user", "", time() - 3600, "/");

echo "Cookie has been deleted! <a


href='set_cookie.php'>Set cookie again</a>";
?>

6. Write a PHP script to demonstrate the use of


$_FILES to upload a file.

(upload_form.html)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>

<h1>Upload a File</h1>

<!-- Form to upload a file -->


<form action="upload.php" method="post"
enctype="multipart/form-data">
<label for="file">Choose file to upload:</label>
<input type="file" name="file" id="file"
required><br><br>
<input type="submit" value="Upload File"
name="submit">
</form>

</body>
</html>

(upload.php)

<?php
// Check if the form is submitted and a file is
uploaded
if (isset($_POST['submit'])) {
// Check if the file was uploaded without any errors
if (isset($_FILES['file']) && $_FILES['file']['error'] ==
0) {

// Define the allowed file types (optional)


$allowed_types = ['image/jpeg', 'image/png',
'application/pdf'];

// Get the file details


$file_name = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];

// Check if the file type is allowed


if (in_array($file_type, $allowed_types)) {
// Define the target directory where the file
will be uploaded
$target_dir = "uploads/";

// Create the target directory if it doesn't exist


if (!is_dir($target_dir)) {
mkdir($target_dir, 0777, true);
}

// Generate a unique name for the file to avoid


overwriting existing files
$target_file = $target_dir .
basename($file_name);

// Move the uploaded file to the target


directory
if (move_uploaded_file($file_tmp,
$target_file)) {
echo "The file " . basename($file_name) . "
has been uploaded successfully.";
} else {
echo "Sorry, there was an error uploading
your file.";
}
} else {
echo "Sorry, only JPEG, PNG, and PDF files are
allowed.";
}
} else {
echo "No file uploaded or an error occurred
during upload.";
}
}
?>

7. Write a PHP script to demonstrate the use of


$_SERVER to display server information.

(server_info.php)

<?php
// Display basic server information using $_SERVER
echo "<h1>Server Information</h1>";

// Server software (e.g., Apache, Nginx)


echo "<b>Server Software:</b> " .
$_SERVER['SERVER_SOFTWARE'] . "<br>";

// Server name (e.g., localhost, example.com)


echo "<b>Server Name:</b> " .
$_SERVER['SERVER_NAME'] . "<br>";

// Server IP address
echo "<b>Server IP:</b> " .
$_SERVER['SERVER_ADDR'] . "<br>";

// Server port
echo "<b>Server Port:</b> " .
$_SERVER['SERVER_PORT'] . "<br>";

// Document root (directory where the server is


serving files from)
echo "<b>Document Root:</b> " .
$_SERVER['DOCUMENT_ROOT'] . "<br>";

// HTTP method used (GET, POST, etc.)


echo "<b>Request Method:</b> " .
$_SERVER['REQUEST_METHOD'] . "<br>";

// The script file being executed (e.g.,


server_info.php)
echo "<b>Current Script Name:</b> " .
$_SERVER['SCRIPT_NAME'] . "<br>";

// The URI of the current request (e.g.,


/path/to/page)
echo "<b>Request URI:</b> " .
$_SERVER['REQUEST_URI'] . "<br>";

// Client's IP address
echo "<b>Client IP:</b> " .
$_SERVER['REMOTE_ADDR'] . "<br>";

// The referring page, if available (e.g., if the user


clicked a link to this page)
echo "<b>Referring URL:</b> " .
(isset($_SERVER['HTTP_REFERER']) ?
$_SERVER['HTTP_REFERER'] : 'No Referrer') . "<br>";

// The User-Agent string (browser and OS


information)
echo "<b>User-Agent:</b> " .
$_SERVER['HTTP_USER_AGENT'] . "<br>";
?>

8. Write a PHP script to demonstrate the use of $_ENV


variables.

(env_example.php)

<?php
// Set environment variables using putenv()
putenv("APP_NAME=MyPHPApp");
putenv("APP_ENV=development");
putenv("APP_VERSION=1.0.0");

// Display environment variables using $_ENV


echo "<h1>Environment Variables</h1>";
echo "<b>App Name:</b> " . getenv("APP_NAME") .
"<br>";
echo "<b>App Environment:</b> " .
getenv("APP_ENV") . "<br>";
echo "<b>App Version:</b> " .
getenv("APP_VERSION") . "<br>";

// Alternatively, using $_ENV array (same values as


using getenv)
echo "<br><b>Using \$_ENV array:</b><br>";
echo "<b>App Name:</b> " . $_ENV['APP_NAME'] .
"<br>";
echo "<b>App Environment:</b> " .
$_ENV['APP_ENV'] . "<br>";
echo "<b>App Version:</b> " .
$_ENV['APP_VERSION'] . "<br>";
?>

9. Write a PHP script to demonstrate the use of


$_GLOBALS.

<?php
// Define global variables
$globalVar1 = "I am a global variable!";
$globalVar2 = 42;

// Function that modifies global variables using


$_GLOBALS
function modifyGlobalVariables() {
// Access and modify global variables using
$_GLOBALS
$_GLOBALS['globalVar1'] = "Global variable 1 has
been modified!";
$_GLOBALS['globalVar2'] = 100;
}

// Display the global variables before modification


echo "<h1>Global Variables Before
Modification</h1>";
echo "globalVar1: " . $globalVar1 . "<br>";
echo "globalVar2: " . $globalVar2 . "<br>";

// Call the function to modify the global variables


modifyGlobalVariables();

// Display the global variables after modification


echo "<h1>Global Variables After
Modification</h1>";
echo "globalVar1: " . $globalVar1 . "<br>";
echo "globalVar2: " . $globalVar2 . "<br>";
?>

10. Write a PHP script to demonstrate cross-page data


transfer using $_SESSION.

form.php

<?php
// Start the session
session_start();
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cross-Page Data Transfer</title>
</head>
<body>

<h1>Enter Your Name</h1>

<!-- Form to input data -->


<form action="store_data.php" method="post">
<label for="name">Your Name:</label>
<input type="text" id="name" name="name"
required>
<input type="submit" value="Submit">
</form>

</body>
</html>

store_data.php

<?php
// Start the session to store data
session_start();

// Check if the form is submitted and the 'name' field


is not empty
if (isset($_POST['name']) && !
empty($_POST['name'])) {
// Store the form data in the session
$_SESSION['user_name'] = $_POST['name'];

// Redirect to the next page (display.php)


header("Location: display.php");
exit(); // Ensure the script stops after the redirect
} else {
echo "Please enter your name.";
}
?>

display.php
<?php
// Start the session to retrieve data
session_start();

// Check if the session variable 'user_name' is set


if (isset($_SESSION['user_name'])) {
// Display the session data
echo "<h1>Hello, " .
htmlspecialchars($_SESSION['user_name']) .
"!</h1>";
} else {
echo "<h1>No data found. Please go back and
enter your name.</h1>";
}
?>

<!-- Provide a link to return to the first page -->


<a href="form.php">Go Back</a>

You might also like