Assignment Php
Assignment Php
<?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";
?>
<?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>
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;
?>
<?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;
?>
<?php
$globalVar = "I am a global variable";
function testScope() {
$localVar = "I am a local variable";
global $globalVar;
echo $localVar . "<br>";
echo $globalVar;
}
testScope();
?>
<?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";
?>
<?php
$string = "Hello, this is a PHP string!";
echo $string;
?>
<?php
$length = 10;
$width = 5;
$area = $length * $width;
echo "The area of the rectangle is: $area";
?>
<?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";
?>
<?php
$var = 10.5;
echo "The type of variable is: " . gettype($var);
?>
<?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);
?>
<?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)
<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
?>
<?php
$isTrue = true;
$isFalse = false;
?>
$nullVar = null;
?>
<?php
$floatNum = 10.75;
$intNum = (int) $floatNum;
?>
<?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.";
}
?>
<?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>";
?>
<?php
?>
10. Write a PHP script to add and multiply numbers of different data types.
<?php
?>
4. Strings
1. Write a PHP script to count the number of characters in a string
<?php
$string = "Hello, PHP!";
$length = strlen($string);
?>
<?php
?>
<?php
?>
<?php
?>
<?php
<?php
?>
<?php
?>
<?php
// Define a string with leading and trailing whitespaces
$string = " Hello, World! ";
<?php
// Define two strings
$string1 = "Hello, World!";
$string2 = "Hello, PHP!";
<?php
// Define a string
$string = "Hello, World! ";
5. Numbers
1. Write a PHP script to perform basic arithmetic operations.
<?php
// Define two numbers
$num1 = 10;
$num2 = 5;
<?php
// Define a number
$number = 25;
// Calculate the square root
$squareRoot = sqrt($number);
<?php
// Generate a random number between 1 and 100
$randomNumber = rand(1, 100);
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];
<?php
// Define a float number
$number = 7.6;
<?php
// Define a string containing a number
$stringNumber = "123.45";
<?php
// Define a number
$number = -25;
<?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);
<?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;
6. Constants
1. Write a PHP script to define and display a constant.
<?php
// Define a constant
define("SITE_NAME", "MyWebsite");
<?php
// Define a constant
define("SITE_NAME", "MyWebsite");
<?php
// Define multiple constants
define("SITE_NAME", "MyWebsite");
define("SITE_URL", "https://www.mywebsite.com");
define("ADMIN_EMAIL", "[email protected]");
<?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);
<?php
// Define constants
define("PI", 3.14159);
define("RADIUS", 5);
<?php
// Define constants
define("PI", 3.14159);
define("RADIUS", 5);
<?php
// Define a constant
define("GREETING", "Welcome to MyWebsite!");
<?php
// Define a constant
define("SITE_NAME", "MyWebsite");
// Demonstrating immutability
echo "Constants cannot be changed after they are defined.";
?>
<?php
// Define constants using the const keyword
const SITE_NAME = "MyWebsite";
const SITE_URL = "https://www.mywebsite.com";
<?php
// Define a class with constants
class Website {
const SITE_NAME = "MyWebsite";
const SITE_URL = "https://www.mywebsite.com";
7. Operators
1. Write a PHP script to demonstrate arithmetic operators.
<?php
// Define two numbers
$num1 = 10;
$num2 = 5;
<?php
// Define two numbers
$num1 = 10;
$num2 = 5;
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";
?>
<?php
// Define two boolean values
$bool1 = true;
$bool2 = false;
<?php
// Define two numbers
$num1 = 6; // 110 in binary
$num2 = 3; // 011 in binary
<?php
// Define a number
$number = 10;
<?php
// Define a number
$number = 10;
<?php
// Define a variable
$number = 10;
// 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";
?>
<?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
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;
<?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);
<?php
// Define an array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
<?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;
}
<?php
// Define an array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
<?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;
<?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;
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';
}
<?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;
<?php
// Function with default parameters
function greet($name = "Guest", $message = "Welcome to
PHP!") {
echo "Hello, $name! $message\n";
}
<?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];
<?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];
<?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;
<?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";
?>
<?php
// Simple anonymous function
$greet = function($name) {
return "Hello, $name!";
};
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"];
<?php
// Create an associative array
$person = [
"name" => "John",
"age" => 25,
"city" => "New York"
];
<?php
// Create two arrays
$array1 = ["Apple", "Banana", "Orange"];
$array2 = ["Grapes", "Mango", "Pineapple"];
<?php
// Create an array
$numbers = [5, 3, 8, 1, 2, 7];
<?php
// Define an array
$array = array(1, 2, 3, 4, 5);
<?php
// Define an array
$array = array(10, 20, 30, 40, 50);
<?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")
)
);
<?php
// Define an array with duplicate values
$array = array(1, 2, 3, 4, 5, 2, 3, 6, 4);
<?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);
<?php
// Define an array with some duplicate values
$array = array(1, 2, 2, 3, 4, 5, 5, 6);
// Get the keys of the filtered array, which are the unique
elements
$uniqueElements = array_keys($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>
</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'];
(form.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>POST Method Example</title>
</head>
<body>
</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'];
(form.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>$_REQUEST Example</title>
</head>
<body>
</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!";
}
?>
(set_session.php)
<?php
// Start the session
session_start();
// 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();
(destroy_session.php)
<?php
// Start the session
session_start();
(set_cookie.php)
<?php
// Set a cookie that expires in 1 hour (3600 seconds)
setcookie("user", "JohnDoe", time() + 3600, "/");
(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, "/");
(upload_form.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload File</title>
</head>
<body>
<h1>Upload a File</h1>
</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) {
(server_info.php)
<?php
// Display basic server information using $_SERVER
echo "<h1>Server Information</h1>";
// Server IP address
echo "<b>Server IP:</b> " .
$_SERVER['SERVER_ADDR'] . "<br>";
// Server port
echo "<b>Server Port:</b> " .
$_SERVER['SERVER_PORT'] . "<br>";
// Client's IP address
echo "<b>Client IP:</b> " .
$_SERVER['REMOTE_ADDR'] . "<br>";
(env_example.php)
<?php
// Set environment variables using putenv()
putenv("APP_NAME=MyPHPApp");
putenv("APP_ENV=development");
putenv("APP_VERSION=1.0.0");
<?php
// Define global variables
$globalVar1 = "I am a global variable!";
$globalVar2 = 42;
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>
</body>
</html>
store_data.php
<?php
// Start the session to store data
session_start();
display.php
<?php
// Start the session to retrieve data
session_start();