0% found this document useful (0 votes)
29 views40 pages

WBP Solved Practical Final

The document contains various PHP programming tasks including demonstrating operators, creating HTML forms for arithmetic operations, validating user input, and displaying numbers and factorials using loops. It also includes database creation and record insertion examples. Each task is accompanied by PHP code snippets and expected outputs.

Uploaded by

Anshika Kothari
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)
29 views40 pages

WBP Solved Practical Final

The document contains various PHP programming tasks including demonstrating operators, creating HTML forms for arithmetic operations, validating user input, and displaying numbers and factorials using loops. It also includes database creation and record insertion examples. Each task is accompanied by PHP code snippets and expected outputs.

Uploaded by

Anshika Kothari
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/ 40

Question 1

1) Write a PHP program to demonstrate Ternary, Null coalescing and Bitwise Operators .

<?php
// Ternary Operator
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo "Ternary Operator:\n";
echo "Age: $age - Status: $status\n""\n";

// Null Coalescing Operator


$name = null;
$defaultName = $name ?? "Guest";
echo "\n Null Coalescing Operator:\n";
echo "Name: $defaultName\n\n";

// Bitwise Operators
$a = 6; // Binary: 110
$b = 3; // Binary: 011

echo "Bitwise Operators:\n";


echo "a = $a, b = $b\n";
echo "a & b (AND) = " . ($a & $b) . "\n"; // 110 & 011 = 010 => 2
echo "a | b (OR) = " . ($a | $b) . "\n"; // 110 | 011 = 111 => 7
echo "a ^ b (XOR) = " . ($a ^ $b) . "\n"; // 110 ^ 011 = 101 => 5
echo "~a (NOT) = " . (~$a) . "\n"; // ~110 = ...1111111111111001 (2's complement) => -7
echo "a << 1 (Left Shift) = " . ($a << 1) . "\n"; // 110 << 1 = 1100 => 12
echo "a >> 1 (Right Shift) = " . ($a >> 1) . "\n"; // 110 >> 1 = 11 => 3
?>
2) Create a HTML form named “multiformdemo.html” that accepts two numbers from the
user.(Include two labels: 'Enter first number' and 'Enter second number', along with two
textboxes for number inputs, and four submit buttons)and Write PHP code to perform
basic arithmetic operations (addition, subtraction, multiplication, and division) based on
the button the user clicks.

Form.html
<!DOCTYPE html>
<html>
<head>
<title>Multi Operation Form</title>
</head>
<body>
<h2>Simple Calculator</h2>
<form action="calculate.php" method="post">
<label>Enter first number:</label>
<input type="number" name="num1" required><br><br>

<label>Enter second number:</label>


<input type="number" name="num2" required><br><br>

<input type="submit" name="operation" value="Add">


<input type="submit" name="operation" value="Subtract">
<input type="submit" name="operation" value="Multiply">
<input type="submit" name="operation" value="Divide">
</form>
</body>
</html>
Calculate.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
$operation = $_POST['operation'];

echo "<h2>Result:</h2>";

switch($operation) {
case "Add":
echo "$num1 + $num2 = " . ($num1 + $num2);
break;
case "Subtract":
echo "$num1 - $num2 = " . ($num1 - $num2);
break;
case "Multiply":
echo "$num1 * $num2 = " . ($num1 * $num2);
break;
case "Divide":
if ($num2 != 0) {
echo "$num1 / $num2 = " . ($num1 / $num2);
} else {
echo "Error: Division by zero!";
}
break;
default:
echo "Invalid operation selected.";
}
}
?>
Output:

Form.html

Simple Calculator
Enter first number:

Enter second number:

Add Subtract Multiply Divide

Question 2
1) Write a PHP program to demonstrate Break and Continue Statement

<?php
echo "Demonstrating break and continue in a loop:<br><br>";

for ($i = 1; $i <= 10; $i++) {


if ($i == 4) {
echo "Skipping number 4 using continue<br>";
continue; // Skips the rest of the loop when i = 4
}

if ($i == 8) {
echo "Breaking loop at number 8 using break<br>";
break; // Stops the loop when i = 8
}

echo "Number: $i<br>";


}
?>

Output:
Demonstrating break and continue in a loop:

Number: 1
Number: 2
Number: 3
Skipping number 4 using continue
Number: 5
Number: 6
Number: 7
Breaking loop at number 8 using break
2) Create a HTML form named “evenodddemo.html” that accepts a number from the user.
(Include a label 'Enter number', a textbox for number input, and a Submit button) and
Write a PHP code to determine whether the given number is odd or even
Html
<!-- evenodddemo.html -->
<!DOCTYPE html>
<html>
<head>
<title>Even or Odd Checker</title>
</head>
<body>
<h2>Check Even or Odd</h2>
<form action="evenodd.php" method="post">
<label>Enter number:</label>
<input type="number" name="number" required>
<input type="submit" value="Check">
</form>
</body>
</html>

Php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$num = $_POST['number'];

if ($num % 2 == 0) {
echo "<h3>The number $num is Even.</h3>";
} else {
echo "<h3>The number $num is Odd.</h3>";
}
}
?>
Output:

Check Even or Odd


Check
Enter number:

The number 5 is Odd.

Question 3
1) Write a PHP program to display even numbers from 1-50 (using for ,while and do..while loop)

<?php
echo "<h3>Using for loop:</h3>";
for ($i = 1; $i <= 50; $i++) {
if ($i % 2 == 0) {
echo "$i ";
}
}

echo "<h3>Using while loop:</h3>";


$i = 1;
while ($i <= 50) {
if ($i % 2 == 0) {
echo "$i ";
}
$i++;
}

echo "<h3>Using do..while loop:</h3>";


$i = 1;
do {
if ($i % 2 == 0) {
echo "$i ";
}
$i++;
} while ($i <= 50);
?>

Output:
Using for loop:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

Using while loop:


2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

Using do..while loop:


2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50

2) Write a PHP program to validate the name, email, password and mobile_no fields of html
form
Html:

<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<h2>Customer Details Form</h2>
<form action="display_customer.php" method="post">
<label>Customer Name:</label><br>
<input type="text" name="name" pattern= “/^[A-Za-z ]{2,}$/”
required><br><br>

<label>Address:</label><br>
<textarea name="address" rows="4" cols="30"
required></textarea><br><br>

<label>Mobile Number:</label><br>
<input type="tel" name="mobile" pattern="[0-9]{10}"
required><br><br>

<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>

<label>Email Id:</label><br>
<input type="text" name="email" pattern="validate_email.php"
required><br><br>

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


</form>
</body>
</html>

Email_validate:

<?php if (filter_var($email, FILTER_VALIDATE_EMAIL)) {


echo "Valid email address.";
} else {
echo "Invalid email address.";
}?>

Php:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$address = $_POST["address"];
$mobile = $_POST["mobile"];
$dob = $_POST["dob"];
$email = $_POST["email"];

echo "<h2>Customer Submitted Details</h2>";


echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Address: " . nl2br(htmlspecialchars($address)) . "<br>";
echo "Mobile Number: " . htmlspecialchars($mobile) . "<br>";
echo "Date of Birth: " . htmlspecialchars($dob) . "<br>";
echo "Email Address " . htmlspecialchars($email) . "<br>";
}
?>

Output:
Customer Details Form
Customer Name:

Address:

Mobile Number:

Date of Birth:

Email Id:

Submit

Question 4

1) Write a PHP program to display numbers from 1to 10 (using for ,while and do..while loop)

<?php
echo "<h3>Using for loop:</h3>";
for ($i = 1; $i <= 10; $i++) {
echo "$i ";
}

echo "<h3>Using while loop:</h3>";


$i = 1;
while ($i <= 10) {
echo "$i ";
$i++;
}
echo "<h3>Using do..while loop:</h3>";
$i = 1;
do {
echo "$i ";
$i++;
} while ($i <= 10);
?>
Output:
Using for loop:
1 2 3 4 5 6 7 8 9 10

Using while loop:


1 2 3 4 5 6 7 8 9 10

Using do..while loop:


1 2 3 4 5 6 7 8 9 10

2) Create customer form like customer name, address, mobile no, date of birth using different
form of input elements and display user inserted values in new PHP form
Html
<!DOCTYPE html>
<html>
<head>
<title>Customer Form</title>
</head>
<body>
<h2>Customer Details Form</h2>
<form action="display_customer.php" method="post">
<label>Customer Name:</label><br>
<input type="text" name="name" required><br><br>

<label>Address:</label><br>
<textarea name="address" rows="4" cols="30" required></textarea><br><br>

<label>Mobile Number:</label><br>
<input type="tel" name="mobile" pattern="[0-9]{10}" required><br><br>

<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>

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


</form>
</body>
</html>

Php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$address = $_POST["address"];
$mobile = $_POST["mobile"];
$dob = $_POST["dob"];

echo "<h2>Customer Submitted Details</h2>";


echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Address: " . nl2br(htmlspecialchars($address)) . "<br>";
echo "Mobile Number: " . htmlspecialchars($mobile) . "<br>";
echo "Date of Birth: " . htmlspecialchars($dob) . "<br>";
}
?>
Output:

Html

Customer Details Form


Customer Name:

Address:
Mobile Number:

Date of Birth:

Submit

php:

Customer Submitted Details


Name: janhavi
Address: mumbai
Mobile Number: 8356085725
Date of Birth: 2025-04-08

Question 5
1) Write a PHP program to display factorial of number (using for ,while and do..while loop).

<?php
$number = 5;

// Using for loop


$fact = 1;
for ($i = 1; $i <= $number; $i++) {
$fact *= $i;
}
echo "<h3>Factorial of $number using for loop is: $fact</h3>";

// Using while loop


$fact = 1;
$i = 1;
while ($i <= $number) {
$fact *= $i;
$i++;
}
echo "<h3>Factorial of $number using while loop is: $fact</h3>";

// Using do..while loop


$fact = 1;
$i = 1;
do {
$fact *= $i;
$i++;
} while ($i <= $number);
echo "<h3>Factorial of $number using do..while loop is: $fact</h3>";
?>
Output:
Factorial of 5 using for loop is: 120
Factorial of 5 using while loop is: 120
Factorial of 5 using do..while loop is: 120

2) Write a PHP programs to create database, create table and insert records in a table.

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS customerdb";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully or already exists.<br>";
} else {
echo "Error creating database: " . $conn->error;
}

// Select the database


$conn->select_db("customerdb");

// Create table
$sql = "CREATE TABLE IF NOT EXISTS customers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
email VARCHAR(50),
mobile VARCHAR(15)
)";
if ($conn->query($sql) === TRUE) {
echo "Table 'customers' created successfully or already exists.<br>";
} else {
echo "Error creating table: " . $conn->error;
}

// Insert record
$sql = "INSERT INTO customers (name, email, mobile)
VALUES ('John Doe', '[email protected]', '9876543210')";
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully.";
} else {
echo "Error inserting record: " . $conn->error;
}

$conn->close();
?>
Output:
Database created successfully or already exists.
Table 'customers' created successfully or already exists.
New record inserted successfully.

Question 6
1) Write a PHP program to find largest of three numbers

<?php
$a = 25;
$b = 42;
$c = 18;

echo "<h3>Numbers: A = $a, B = $b, C = $c</h3>";

if ($a >= $b && $a >= $c) {


echo "Largest number is A = $a";
} elseif ($b >= $a && $b >= $c) {
echo "Largest number is B = $b";
} else {
echo "Largest number is C = $c";
}
?>

Output:
Numbers: A = 25, B = 42, C = 18
Largest number is B = 42

2) Write a PHP program to Insert data into employee table and Select data from employee
table.

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$conn->query("CREATE DATABASE IF NOT EXISTS companydb");
$conn->select_db("companydb");

// Create employee table


$sql = "CREATE TABLE IF NOT EXISTS employee (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
position VARCHAR(50),
salary DECIMAL(10,2)
)";
$conn->query($sql);

// Insert sample data


$insert = "INSERT INTO employee (name, position, salary)
VALUES ('Alice', 'Manager', 55000.00)";
$conn->query($insert);

// Select and display data


$result = $conn->query("SELECT * FROM employee");

echo "<h3>Employee Records:</h3>";


if ($result->num_rows > 0) {
echo "<table border='1' cellpadding='5'>";
echo "<tr><th>ID</th><th>Name</th><th>Position</th><th>Salary</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>{$row["id"]}</td>
<td>{$row["name"]}</td>
<td>{$row["position"]}</td>
<td>{$row["salary"]}</td>
</tr>";
}
echo "</table>";
} else {
echo "No employee records found.";
}

$conn->close();
?>
Output:

Employee Records:
ID Name Position Salary

1 Alice Manager 55000.00

Question 7

1) Write a calendar program using switch statement.


<?php
$month_number = 4; // Change this to any number between 1 and 12 to test different months

switch ($month_number) {
case 1:
echo "January";
break;
case 2:
echo "February";
break;
case 3:
echo "March";
break;
case 4:
echo "April";
break;
case 5:
echo "May";
break;
case 6:
echo "June";
break;
case 7:
echo "July";
break;
case 8:
echo "August";
break;
case 9:
echo "September";
break;
case 10:
echo "October";
break;
case 11:
echo "November";
break;
case 12:
echo "December";
break;
default:
echo "Invalid month number! Please enter a number between 1 and 12.";
break;
}
?>
Output:
April
2) Write a PHP program to Update and Delete data from employee table
Updating Data:

<?php
// Create a connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql query to update a record
$sql = "UPDATE emp SET job='Salesman' WHERE ename='Abhijeet' ";
$result=mysqli_query($conn, $sql);
if($result==true){
echo "Record updated successfully";
} else {
echo "Error while updating record: " . mysqli_error($conn);
}
//close connection
mysqli_close($conn);
?>
Delete Data:

<?php
// Create connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql query to delete a record
$sql = "DELETE FROM emp WHERE ename='Abhijeet'";
$result=mysqli_query($conn, $sql);
if($result==true){
echo "Record deleted successfully";
} else {
echo "Error while deleting record: " . mysqli_error($conn);
}
//close connection
mysqli_close($conn);
?>

Output:
Updating Data:
Record updated successfully
Delete Data:
Record deleted successfully

Question 8

1) Write a PHP program creating and traversing an Indexed, Associative and


Multidimensional array(using for loop or foreach loop)

<?php
// 1. Indexed Array
$fruits = ["Apple", "Banana", "Mango", "Orange"];
echo "Indexed Array:<br>";
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "<br>";
}

echo "<br>";

// 2. Associative Array
$student = ["name" => "Amit", "age" => 20, "course" => "BMS"];
echo "Associative Array:<br>";
foreach ($student as $key => $value) {
echo "$key : $value<br>";
}

echo "<br>";

// 3. Multidimensional Array
$employees = [
["id" => 1, "name" => "Ravi", "salary" => 30000],
["id" => 2, "name" => "Neha", "salary" => 35000],
["id" => 3, "name" => "Karan", "salary" => 32000]
];

echo "Multidimensional Array:<br>";


foreach ($employees as $emp) {
foreach ($emp as $key => $value) {
echo "$key: $value ";
}
echo "<br>";
}
?>

Output:
Indexed Array:
Apple
Banana
Mango
Orange

Associative Array:
name : Amit
age : 20
course : BMS

Multidimensional Array:
id: 1 name: Ravi salary: 30000
id: 2 name: Neha salary: 35000
id: 3 name: Karan salary: 32000
2) Write a PHP program for sending mail

<?php
$to = "[email protected]";
$subject = "Test Email from PHP";
$message = "Hello, this is a test email sent from a PHP script.";
$headers = "From:[email protected]";
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Failed to send email.";
}
?>

Question 9
1) Write a PHP program to demonstrate Sort functions for Arrays(sort(),rsort(),asort() ,
ksort() , arsort(),krsort())

<?php

// Indexed Array

$numbers = [4, 2, 8, 5, 1];

echo "Original Indexed Array:\n";

print_r($numbers);

// sort() – Sort in ascending order

sort($numbers);

echo "\nsort() – Ascending Order:\n";

print_r($numbers);

// rsort() – Sort in descending order

rsort($numbers);

echo "\nrsort() – Descending Order:\n";

print_r($numbers);

echo "\n";

// Associative Array

$person = [

"name" => "John",


"age" => 25,

"city" => "New York"

];

echo "Original Associative Array:\n";

print_r($person);

// asort() – Sort associative array in ascending order (by values)

asort($person);

echo "\nasort() – Ascending Order (by values):\n";

print_r($person);

// ksort() – Sort associative array by keys in ascending order

ksort($person);

echo "\nksort() – Ascending Order (by keys):\n";

print_r($person);

// arsort() – Sort associative array in descending order (by values)

arsort($person);

echo "\narsort() – Descending Order (by values):\n";

print_r($person);

// krsort() – Sort associative array by keys in descending order


krsort($person);

echo "\nkrsort() – Descending Order (by keys):\n";

print_r($person);

?>

Output:

Original Indexed Array:


Array ( [0] => 4 [1] => 2 [2] => 8 [3] => 5 [4] => 1 )
sort() – Ascending Order:
Array ( [0] => 1 [1] => 2 [2] => 4 [3] => 5 [4] => 8 )
rsort() – Descending Order:
Array ( [0] => 8 [1] => 5 [2] => 4 [3] => 2 [4] => 1 )
Original Associative Array:
Array ( [name] => John [age] => 25 [city] => New York )
asort() – Ascending Order (by values):
Array ( [age] => 25 [name] => John [city] => New York )
ksort() – Ascending Order (by keys):
Array ( [age] => 25 [city] => New York [name] => John )
arsort() – Descending Order (by values):
Array ( [city] => New York [name] => John [age] => 25 )
krsort() – Descending Order (by keys):
Array ( [name] => John [city] => New York [age] => 25 )

2) Write a PHP program to count total number of rows in the database table

<?php
// Create connection
$conn = mysqli_connect("localhost", "root","","company");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT count(*) as total_emp FROM emp ";
$result = mysqli_query($conn, $sql);
//Loop through each row
foreach($result as $res){
echo "Total number of employees are:".$res['total_emp'];
}
mysqli_close($conn);
?>
Output:
Total number of employees are:2

Question 10

1) Write a PHP program to demonstrate use of various built-in string function

<?php
// Original string
$string = "Hello, World! This is PHP string functions demonstration.";

// 1. strlen() – Get string length


echo "Length of the string: " . strlen($string) ."<br>";

// 2. strpos() – Find position of the first occurrence of a substring


echo "Position of 'World': " . strpos($string, "World") . "<br>";

// 3. strtoupper() – Convert string to uppercase


echo "Uppercase string: " . strtoupper($string) . "<br>";

// 4. strtolower() – Convert string to lowercase


echo "Lowercase string: " . strtolower($string) . "<br>";

// 5. substr() – Get a portion of the string


echo "Substring (from position 7 to 11): " . substr($string, 7, 11) .
"<br>";
// 6. str_replace() – Replace all occurrences of the search string with the
replacement string
echo "Replace 'World' with 'PHP': " . str_replace("World", "PHP", $string) .
"<br>";

// 7. trim() – Remove whitespace from the beginning and end of the string
$trimmed = " Hello, World! ";
echo "Trimmed string: '" . trim($trimmed) . "<br>";

// 8. ucfirst() – Capitalize the first letter of a string


echo "Capitalize first letter: " . ucfirst("hello") . "<br>";

// 9. ucwords() – Capitalize the first letter of each word in a string


echo "Capitalize first letter of each word: " . ucwords("hello world") .
"<br>";

// 10. strrev() – Reverse the string


echo "Reversed string: " . strrev($string) . "<br>";

// 11. strstr() – Find the first occurrence of a substring


echo "Substring from 'World': " . strstr($string, "World") . "<br>";

// 12. explode() – Split a string by a delimiter


$words = explode(" ", $string);
echo "Exploded words: <br>";
print_r($words);

// 13. implode() – Join array elements into a string


$sentence = implode(" ", $words);
echo "Imploded sentence: " . $sentence . "<br>";

// 14. printf() – Output a formatted string


printf("Formatted string: %s<br>", strtoupper($string));

// 15. strpos() – Find the first occurrence of a substring (again, just for
demonstration)
$position = strpos($string, "PHP");
echo "Position of 'PHP' in string: " . $position . "<br>";
?>

Output:
Length of the string: 57
Position of 'World': 7
Uppercase string: HELLO, WORLD! THIS IS PHP STRING FUNCTIONS DEMONSTRATION.
Lowercase string: hello, world! this is php string functions demonstration.
Substring (from position 7 to 11): World! This
Replace 'World' with 'PHP': Hello, PHP! This is PHP string functions demonstration.
Trimmed string: 'Hello, World!
Capitalize first letter: Hello
Capitalize first letter of each word: Hello World
Reversed string: .noitartsnomed snoitcnuf gnirts PHP si sihT !dlroW ,olleH
Substring from 'World': World! This is PHP string functions demonstration.
Exploded words:
Array ( [0] => Hello, [1] => World! [2] => This [3] => is [4] => PHP [5] => string [6] => functions [7] =>
demonstration. ) Imploded sentence: Hello, World! This is PHP string functions demonstration.
Formatted string: HELLO, WORLD! THIS IS PHP STRING FUNCTIONS DEMONSTRATION.
Position of 'PHP' in string: 22
2) Write a PHP programs to implements Single, Multilevel and Multiple inheritances.
Multiple:

<?php
// First Interface
interface Animal {
public function eat();
}

// Second Interface
interface Pet {
public function play();
}

// Class implementing both Animal and Pet interfaces


class Dog implements Animal, Pet {
public function eat() {
echo "Eating...\n";
}

public function play() {


echo "Playing...\n";
}
}

// Creating an object of Dog class


$dog = new Dog();
$dog->eat(); // Method from Animal interface
$dog->play(); // Method from Pet interface
?>

Single:

<?php
class college {
public $name;
protected $code;
public function __construct($n,$c) {
$this->name = $n;
$this->code = $c;
}
}
class student extends college {
public $sname;
public function __construct($n,$c,$sn) {
parent::__construct($n,$c); // Call parent constructor
$this->sname = $sn;
}
public function display(){
echo "<br>College Name=" .$this->name;
echo "<br>College Code=" .$this->code;
echo "<br>Student Name=" .$this->sname;
}
}
$obj = new student('BVIT','0027','Rajesh');
// This will call the college constructor to set the "name" and "code" property
// and then set the "sname" property within the student constructor
$obj->display();
?>

Multilevel:

class Student1{
public $rollno;
public $name;
function display1(){
echo "<br>Roll no:".$this->rollno;
echo "<br>Student name:".$this->name;
}
}
class Test extends Student1{
public $sub1,$sub2,$sub3;
function display2(){
echo "<br>Mark of subject1:".$this->sub1;
echo "<br>Mark of subject2:".$this->sub2;
echo "<br>Mark of subject3:".$this->sub3;
}
}
class Result extends Test{
public $total;
function __construct($r,$n,$s1,$s2,$s3){
$this->rollno=$r;
$this->name=$n;
$this->sub1=$s1;
$this->sub2=$s2;
$this->sub3=$s3;
}
function display3(){
$this->total=($this->sub1 + $this->sub2+$this->sub3);
echo "<br> Total marks:".$this->total;
echo "<br> Percentage:" .($this->total/3);
}
}
$obj=new Result(3401,'Raj',50,60,70);
$obj->display1();
$obj->display2();
$obj->display3();
?>

Output:

Multiple:
Eating... Playing...
Single:
College Name=BVIT
College Code=0027
Student Name=Rajesh
Multilevel:
Roll no:3401
Student name:Raj
Mark of subject1:50
Mark of subject2:60
Mark of subject3:70
Total marks:180
Percentage:60
Question 11

1) Write a PHP programs to calculate length of string and count number of words in string
without using string functions .

<?php
$str="Hello World!";
for($i=0;isset($str[$i]);$i++){
}
echo "Length of string is:".$i;
$arr=explode(" ",$str);
echo "<br>number of words in a string are:".count($arr);
?>
Output:
Length of string is:12
Number of words in a string are:2

2) Develop a PHP programs to demonstrate function overloading and overriding.


Overriding:

<?php
// Class demonstrating function overriding
class Animal {
// Method in parent class
public function speak() {
echo "Animal speaks\n";
}
}

class Dog extends Animal {


// Overriding the speak method in the child class
public function speak() {
echo "Dog barks\n";
}
}

// Object of parent class


$animal = new Animal();
$animal->speak(); // Outputs: Animal speaks

// Object of child class


$dog = new Dog();
$dog->speak(); // Outputs: Dog barks

echo "\n";

// Class demonstrating function overloading


class DynamicMethods {
// Magic method to handle function overloading
public function __call($name, $arguments) {
echo "Called method: $name\n";
echo "Arguments passed: " . implode(", ", $arguments) . "\n";
}
}

// Object of class with dynamic method handling


$obj = new DynamicMethods();

// Calling a method that doesn't exist


$obj->add(10, 20); // Outputs: Called method: add | Arguments passed: 10, 20

$obj->multiply(5, 4); // Outputs: Called method: multiply | Arguments passed: 5, 4


?>
Overloading:

<?php
// Creates shape class
class shape{
// __call is magic function which accepts function name and arguments
function __call($name_of_function, $arguments){
// It will check the function name
if($name_of_function == 'area'){
switch (count($arguments)){
//If there is only one argument then it returns area of circle
case 1:
return (3.14 * $arguments[0]*$arguments[0]);
break;
//If there are two arguments then it returns area of rectangle
case 2:
return ($arguments[0]*$arguments[1]);
break;
}
}
}
}
//creating a object of shape class
$obj = new Shape();
//calling area method for circle
echo ("<br> Area of circle is:".$obj->area(2));
//calling area method for rectangle
echo ("<br> Area of rectangle is:".$obj->area(4,2));
?>
Output:
Animal speaks Dog barks Called method: add Arguments passed: 10, 20 Called method: multiply
Arguments passed: 5, 4
Overloading:
Area of circle is:12.56
Area of rectangle is:8

Question 12

1) Write a PHP programs to demonstrate Parameterized function, Variable function and <?
php
echo "<h3>1. Parameterized Function</h3>";

function multiply($a, $b) {


$product = $a * $b;
echo "Multiplication is: $product <br>";
}
multiply(5, 4); // Calling normal parameterized function

// --------------------------------------
echo "<h3>2. Variable Function</h3>";

function greet($name) {
echo "Hello, $name! Welcome to PHP Variable Functions.<br>";
}

$func = "greet"; // Store function name in variable


$func("Alice"); // Calling the variable function

// --------------------------------------

echo "<h3>3. Anonymous Function (with Closure)</h3>";

$x = 15;
$y = 25;

// Define anonymous function with closure


$anonFunc = function() use ($x, $y) {
$sum = $x + $y;
echo "Sum using anonymous function (closure): $sum";
};

$anonFunc(); // Call the anonymous function


?>
Output:

1. Parameterized Function
Multiplication is: 20

2. Variable Function
Hello, Alice! Welcome to PHP Variable Functions.
3. Anonymous Function (with Closure)
Sum using anonymous function (closure): 40
2) Write PHP program for cloning of an object

<?php

class Car {
public $brand;
public function __construct($brand) {
$this->brand = $brand;
}
}
$car1 = new Car("Toyota");
$car2 = clone $car1; // Cloning the object
$car2->brand = "Honda"; // Changing the cloned object's property
echo $car1->brand; // Output: Toyota
echo $car2->brand; // Output: Honda
?>
Output:
ToyotaHonda

Question 13

1) Write a PHP programs to draw a rectangle filled with red color and to display text on
image

<?php
// Ensure no output before headers
ob_clean();

// Set the content type to image


header("Content-Type: image/png");

// Create a blank image (300x150)


$image = imagecreate(300, 150);

// Allocate colors
$red = imagecolorallocate($image, 255, 0, 0); // Red background
$white = imagecolorallocate($image, 255, 255, 255); // White text

// Fill background with red (default on imagecreate)


imagefilledrectangle($image, 0, 0, 300, 150, $red);

// Draw text
imagestring($image, 5, 80, 60, "Hello, Image!", $white);
// Output image
imagepng($image);

// Free up memory
imagedestroy($image);
?>

2) Write a PHP programs to demonstrate Serialization and Introspection

<?php

// Define a simple class

class Student {

public $name;

public $age;

public function __construct($name, $age) {

$this->name = $name;

$this->age = $age;

public function greet() {

return "Hello, I am $this->name.";

// Create an object

$student = new Student("Alice", 22);


// ----------- Serialization -----------

echo "<h3>Serialization</h3>";

// Serialize the object

$serialized = serialize($student);

echo "Serialized Data:<br>" . $serialized . "<br><br>";

// Unserialize the object

$unserialized = unserialize($serialized);

echo "Unserialized Object:<br>";

echo "Name: " . $unserialized->name . "<br>";

echo "Age: " . $unserialized->age . "<br><br>";

// ----------- Introspection -----------

echo "<h3>Introspection</h3>";

// Get class name

echo "Class Name: " . get_class($student) . "<br><br>";

// Get class methods

echo "Methods:<br>";
print_r(get_class_methods($student));

echo "<br><br>";

// Get class properties

echo "Properties:<br>";

print_r(get_object_vars($student));

?>

Output:

Serialization
Serialized Data:
O:7:"Student":2:{s:4:"name";s:5:"Alice";s:3:"age";i:22;}

Unserialized Object:
Name: Alice
Age: 22

Introspection
Class Name: Student

Methods:
Array ( [0] => __construct [1] => greet )

Properties:
Array ( [name] => Alice [age] => 22 )

Question 14

1) Write a PHP program to create a class as “Rectangle” with two properties length and
width. Calculate area and perimeter of rectangle for two objects
<?php
//Create a class as “Rectangle” with two properties length & width. Calculate perimeter and area of
rectangle.
class Rectangle{
//Declare properties
public $length=0;
public $width=0;
//method to set values to properties
function setdata($l,$w){
$this->length=$l;
$this->width=$w;
}
//method to calculate the perimeter
function calculatePerimeter(){
echo "Perimeter of rectangle is:".(2*($this->length+$this->width));
}
//method to calculate the area of rectangle
function calculateArea(){
echo "<br>Area of rectangle is:".($this->length*$this->width);
}
}
//Create object of rectangle class
$obj1=new Rectangle;
//call the object methods
$obj1->setdata(20,30);
$obj1->calculatePerimeter();
$obj1->calculateArea();
?>
Output:
Perimeter of rectangle is:100
Area of rectangle is:600
2) Write a PHP program to create access, modify and delete a cookie.

Create cookie:

<html>
<body>
<?php
$cookie_name = "user";
$cookie_value = "Amit Patil";
setcookie ($cookie_name, $cookie_value, time () + (86400*30),"/"); // 86400 = 1 day

if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named " . $cookie_name. " is not set!";
}
else {
echo "Cookie " . $cookie_name . " is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p> <b> Note:</b> You might have to reload the page to see the value of the cookie.
</p>

</body>
</html>

Modify Cookie:

<?php
//To modify a cookie, just set (again) the cookie using the setcookie() function
$cookie_name = "user";
$cookie_value = "Rohit Mane";
setcookie($cookie_name, $cookie_value, time() + (86400*30), "/"); // 86400 = 1 day

if(!isset($_COOKIE[$cookie_name])){
echo "Cookie named " . $cookie_name . " is not set!";
}
else{
echo "Cookie " . $cookie_name . " is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>

Delete a cookie:

<?php
//To delete a cookie, use the setcookie () function with an expiration date in the past
setcookie("user"," ",0);
echo "Cookie user is deleted";
?>

Output:

Cookie named user is not set!

Note: You might have to reload the page to see the value of the cookie.

Cookie named user is not set! Cookie user is deleted

Question 15
1) Write a PHP programs to demonstrate default constructor, parameterized constructor
and destructor

Default Constructor:

<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct(){
$this->rollno=10;
$this->name='Raj';
}
//method to display the student data
public function display(){
echo "<br> Rollno:".$this->rollno;
echo "<br> Student name:".$this->name;
}
}
//create a new object of student class
$s1=new student();
//call object method
$s1->display();
?>
Output:
Rollno:10
Student name:Raj
Parameterized Constructor:

<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct($r,$n){
$this->rollno=$r;
$this->name=$n;
}
//method to display the student data
public function display(){
echo "<br> Rollno:".$this->rollno;
echo "<br> Student name:".$this->name;
}
}
//create a new object of student class
$s1=new student(10,'Raj');
//call object method
$s1->display();
$s2=new student(11,'Amit');
$s2->display();
?>

Destructor:

<?php
class student{
//declare properties
public $rollno;
public $name;
//This is initializing the object properties
public function __construct($r,$n) {
$this->rollno=$r;
$this->name=$n;
}
//method to display the student data
public function display(){
echo "<br>Rollno:".$this->rollno;
echo "<br>Student name:".$this->name;
}
//clean up object resources
public function __destruct() {
echo "<br>Destructor is called..";
}
}
//create a new object of student class
$s1=new student(10,'Raj');
//call object method
$s1->display();
$s2=new student(11,'Amit');
$s2->display();
?>
Output:
Rollno:10
Student name:Raj
Rollno:11
Student name:Amit
Destructor is called..
Destructor is called..

2) Write a PHP program to start session, set session variables, get session variables, modify
session Variables and destroy session

1.Start Session and Set Session Variables:

<?php

// Start the session


session_start();
?>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

2.To get and modify Session variables:

<? php
session_start ();
?>
<?php
// display session variables that were set on previous page
echo "<br>Favorite color is: " .$_SESSION["favcolor"];
echo "<br>Favorite animal is: " .$_SESSION["favanimal"];
?>

<?php
session_start();
?>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
echo "Session variable is modified.";
?>

3. To destroy Session:

<?php
session_start();
?>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
echo "Session variables are destroyed.";
?>

Output:

Session variables are set.


Favorite color is: green
Favorite animal is: cat Session variable is modified. Session variables are destroyed.

You might also like