Practical exam Questions
1) Write PHP program to print even numbers upto 10 and sum of them.
<?php
$sum = 0;
for ($i = 2; $i <= 10; $i += 2) {
echo $i . " ";
$sum += $i;
}
echo "<br>Sum of even numbers: " . $sum;
?>
2) Write a PHP program to print prime number upto n.
<?php
echo "Prime numbers up to " . $n . ": ";
for ($i = 2; $i <= $n; $i++) {
$prime = true;
for ($j = 2; $j <= sqrt($i); $j++) {
if ($i % $j == 0) {
$prime = false;
break;
}
}
if ($prime) {
echo $i . " ";
}
}
?>
$n = 10; // Change this value to set the limit
3) Write PHP program to print reverse of number.
<?php
function reverse($number)
{
/* writes number into string. */
$num = (string) $number;
/* Reverse the string. */
$revstr = strrev($num);
/* writes string into int. */
$reverse = (int) $revstr;
return $reverse;
}
echo reverse(23456);
?>
4) Write PHP program to based on multidimensional array.
<?php
$multi_array = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $multi_array[1][2]; // Output: 6
?>
5) Write PHP program to sort associative and multidimensional array.
<?php
$associative_array = array("b" => 2, "a" => 1, "c" => 3);
asort($associative_array);
print_r($associative_array); // Output: Array ( [a] => 1 [b] => 2 [c] => 3 )
$multi_array = array(array(2, 1, 3), array(5, 4, 6), array(8, 7, 9));
foreach ($multi_array as &$sub_array) {
sort($sub_array);
}
print_r($multi_array); // Output: Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3
) [1] => Array ( [0] => 4 [1] => 5 [2] => 6 ) [2] => Array ( [0] => 7 [1] => 8 [2] =>
9))
?>
6) Write PHP program based on interface.
<?php
interface Shape {
public function calculateArea();
}
class Circle implements Shape {
private $radius;
public function __construct($radius) {
$this->radius = $radius;
}
public function calculateArea() {
return pi() * pow($this->radius, 2);
}
}
$circle = new Circle(5);
echo "Area of circle: " . $circle->calculateArea(); // Output: Area of circle:
78.539816339745
?>
7) Write PHP program based on introspection.
<?php
class MyClass {
public $var1;
public $var2 = 'constant';
public function myMethod() {
echo "Hello World!";
}
}
$obj = new MyClass();
echo "<pre>";
print_r(get_class_vars(get_class($obj))); // Output: Array ( [var1] => [var2] =>
constant )
echo "</pre>";
echo "<pre>";
print_r(get_object_vars($obj)); // Output: Array ( [var1] => [var2] => constant )
echo "</pre>";
echo "<pre>";
print_r(get_class_methods('MyClass')); // Output: Array ( [0] => myMethod )
echo "</pre>";
echo "<pre>";
print_r(get_class_methods($obj)); // Output: Array ( [0] => myMethod )
echo "</pre>";
?>
8) Write PHP program based on inheritance.
<?php
class Animal {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function display() {
echo "Name: " . $this->name . ", Color: " . $this->color;
}
}
class Dog extends Animal {
public function sound() {
echo "Woof!";
}
}
$dog = new Dog("Buddy", "Brown");
$dog->display(); // Output: Name: Buddy, Color: Brown
echo "<br>";
$dog->sound(); // Output: Woof!
?>
9) Write PHP program based on session variables ,start ,stop.
<?php
session_start();
$_SESSION['name'] = "John";
echo "Session started. Name is " . $_SESSION['name'] . ".<br>";
session_unset();
session_destroy();
echo "Session stopped.";
?>
10) Write PHP program based on cookies.(isset,name,destroy)
<?php
if (!isset($_COOKIE['name'])) {
setcookie('name', 'John', time() + 3600); // Cookie will expire in 1 hour
echo "Cookie set successfully.";
} else {
echo "Cookie value: " . $_COOKIE['name'];
}
setcookie('name', '', time() - 3600); // Destroying the cookie
echo "<br>Cookie destroyed.";
?>
11) Write PHP program based on create database.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
12) Write PHP program based on select a table from database.
<?php
// Database connection parameters
$servername = "localhost"; // Change this to your database server
$username = "username"; // Change this to your database username
$password = "password"; // Change this to your database password
$database = "database_name"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to select a table from the database
$table_name = "your_table_name"; // Change this to the name of your table
$sql = "SELECT * FROM $table_name";
// Execute query
$result = $conn->query($sql);
// Check if there are rows returned
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
// Output each row's data
foreach ($row as $key => $value) {
echo "$key: $value<br>";
}
echo "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
?>
13) Write PHP program based to insert data in a table.
<?php
// Database connection parameters
$servername = "localhost"; // Change this to your database server
$username = "username"; // Change this to your database username
$password = "password"; // Change this to your database password
$database = "database_name"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sample data to insert
$name = "John Doe";
$email = "
[email protected]";
$age = 30;
// Prepare SQL statement to insert data
$sql = "INSERT INTO your_table_name (name, email, age) VALUES ('$name',
'$email', '$age')";
// Execute SQL statement
if ($conn->query($sql) === TRUE) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close connection
$conn->close();
?>
14) Write PHP program based to update data from a table.
<?php
// Database connection parameters
$servername = "localhost"; // Change this to your database server
$username = "username"; // Change this to your database username
$password = "password"; // Change this to your database password
$database = "database_name"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sample data for update
$newEmail = "
[email protected]";
$idToUpdate = 1; // Assuming you want to update the record with ID 1
// Prepare SQL statement to update data
$sql = "UPDATE your_table_name SET email='$newEmail' WHERE
id=$idToUpdate";
// Execute SQL statement
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
// Close connection
$conn->close();
?>
15) Write PHP program based to delete data from a table.
<?php
// Database connection parameters
$servername = "localhost"; // Change this to your database server
$username = "username"; // Change this to your database username
$password = "password"; // Change this to your database password
$database = "database_name"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sample ID of the record to delete
$idToDelete = 1; // Assuming you want to delete the record with ID 1
// Prepare SQL statement to delete data
$sql = "DELETE FROM your_table_name WHERE id=$idToDelete";
// Execute SQL statement
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
// Close connection
$conn->close();
?>
16) Write PHP program based on string functions (Any four)
<?php
// Sample string
$string = "Hello, World!";
// 1. strlen(): Returns the length of the string
$length = strlen($string);
echo "Length of the string: $length<br>";
// 2. strtoupper(): Converts the string to uppercase
$uppercase = strtoupper($string);
echo "Uppercase string: $uppercase<br>";
// 3. substr(): Returns a part of the string
$substring = substr($string, 0, 5);
echo "Substring: $substring<br>";
// 4. str_replace(): Replaces all occurrences of a search string with a replacement
string
$newString = str_replace("World", "Universe", $string);
echo "After replacement: $newString<br>";
?>
17) Write PHP program based on maths functions (Any four)
<?php
// Sample numbers
$num1 = 10;
$num2 = 5;
// 1. Addition
$sum = $num1 + $num2;
echo "Sum: $sum<br>";
// 2. Subtraction
$diff = $num1 - $num2;
echo "Difference: $diff<br>";
// 3. Multiplication
$product = $num1 * $num2;
echo "Product: $product<br>";
// 4. Division
$quotient = $num1 / $num2;
echo "Quotient: $quotient<br>";
// 5. Square root
$sqrt = sqrt($num1);
echo "Square root of $num1: $sqrt<br>";
// 6. Exponential
$exp = pow($num1, $num2);
echo "$num1 raised to the power of $num2: $exp<br>";
// 7. Absolute value
$abs = abs(-10);
echo "Absolute value of -10: $abs<br>";
// 8. Round to the nearest integer
$round = round(5.4);
echo "Rounded value of 5.4: $round<br>";
?>
18) Write PHP program based on date functions (Any four)
<?php
// Set the default timezone
date_default_timezone_set('UTC');
// 1. Current date and time
$currentDateTime = date('Y-m-d H:i:s');
echo "Current date and time: $currentDateTime<br>";
// 2. Get the day of the week
$dayOfWeek = date('l');
echo "Day of the week: $dayOfWeek<br>";
// 3. Add days to a date
$futureDate = date('Y-m-d', strtotime('+1 week'));
echo "Date one week from now: $futureDate<br>";
// 4. Difference between two dates
$startDate = '2024-01-01';
$endDate = '2024-12-31';
$diff = abs(strtotime($endDate) - strtotime($startDate));
$daysDifference = floor($diff / (60 * 60 * 24));
echo "Days between $startDate and $endDate: $daysDifference<br>";
?>