4 Marks PHP
4 Marks PHP
Ans.
Feature Constant Variable
Definition. A value that cannot be A value that can
changed once set change during
execution
Syntax define("NAME", $name
value); or const NAME = =
value; value;
Prefix No prefix $ prefix
Scope Global by default Scope depends on
where it's declared
b. syntax for each loop with example.
Ans. Syntax:-
foreach($array as $value) {
// code to execute
}
Example:
$colors = array("red", "green", "blue");
foreach($colors as $color) {
echo "$color<br>";
}
c. What are the different type of arrays in php?
Indexed Array – Array with numeric index
Associative Array – Array with named keys
Multidimensional Array – Array containing one or more
arrays
d. Explain methods to submit form.
e. GET Method
a. Sends data through URL
b. Limited data size
c. Example: <form method="get">
f. POST Method
a. Sends data in HTTP body
b. Secure for sensitive data
c. Example: <form method="post">
g. What is session in php? Explin it.
Ans. A session stores user data to be used across multiple
pages.
Example: session_start();
$_SESSION['username'] = "John";
a. Explain if….else statement in php using example.
Ans. $age = 20;
if ($age >= 18) {
echo "Eligible to vote";
} else {
echo "Not eligible";
}
b. Explain difference between clint side scripting & server side
scripting.
Ans.
Feature Client-side Server-side
Executes on User's browser Web server
Language JavaScript, PHP, Python, Node.js
examples HTML, CSS
Usage Form validation, Database access, file
animations handling
c. Write a php program to calculate area of circle and triangle.
Ans. $radius = 5;
$base = 10;
$height = 6;
$circle_area = 3.14 * $radius * $radius;
$triangle_area = 0.5 * $base * $height;
echo "Area of Circle: $circle_area<br>";
echo "Area of Triangle: $triangle_area";
d. Write a note on relational oprator in php.
Ans.
Description Example ($a = 5, $b =
Operator 10)
== Equal to $a == $b (false)
!= Not equal $a != $b (true)
> Greater than $a > $b (false)
< Less than $a < $b (true)
>= Greater than or $a >= $b (false)
equal
<= Less than or equal $a <= $b (true)
e. Explain Response and request object in php.
Request Object: Used to receive data (e.g., $_GET, $_POST,
$_REQUEST)
$name = $_POST['name'];
Response: Sending data/output to browser using echo,
header(), etc.
echo "Welcome $name";
a. Explain introspection in php.
Ans. Introspection is checking the properties, methods, class
structure at runtime.
E.g class Test {
public $x;
function show() {}
}
$reflect = new ReflectionClass('Test');
print_r($reflect->getMethods());
b. Explain in function with defult parameter in php using
example
Ans. function greet($name = "Guest") {
echo "Hello $name";
}
greet(); // Output: Hello Guest
greet("John"); // Output: Hello John
c. Write a php script to accept user’s name and display in on
next page.
Ans. <form action="display.php" method="post">
<input type="text" name="username">
<input type="submit">
</form>
Display:
<?php
$name = $_POST['username'];
echo "Welcome, $name!";
?>
d. Write a php program to display following operators on
string:
i) Sring concatenation
ii) String comparison
Ans. $str1 = "Hello";
$str2 = "World";
// i) Concatenation
echo $str1 . " " . $str2; // Output: Hello World
// ii) Comparison
if ($str1 == $str2) {
echo "Strings are equal";
} else {
echo "Strings are not equal";
}
e. Write a php program to display multiplication table of
entered value.
Ans. $num = 5;
for ($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
a)What are the different types of PHP variables?
ans. In PHP, variables can hold different types of data. The main
types of PHP variables are:
1. String – Stores a sequence of characters.
Example: $name = "John";
2. Integer – Stores whole numbers.
Example: $age = 25;
3. Float (Double) – Stores decimal numbers.
Example: $price = 10.5;
4. Boolean – Stores either true or false.
Example: $isValid = true;
5. Array – Stores multiple values in one variable.
Example: $colors = array("red", "blue",
"green");
6. Object – An instance of a class.
Example: $car = new Car();
7. NULL – A variable with no value assigned.
Example: $x = NULL;
b)What is the difference between GET and POST method?
ans.
Feature GET POST
Visibility Data visible in URL Data not visible in URL
Length Limited length No limit
Security Less secure More secure
Usage Used for data retrieval Used for data
submission
Example example.php?name=John Sent in request body
c) Explain if .... then ..... else in PHP.
ans. The if...else statement is used to make decisions in
PHP.
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
E.g
$age = 20;
if ($age >= 18) {
echo "Eligible to vote";
} else {
echo "Not eligible to vote";
}
d) Explain cookies in PHP
ans. Cookies are used to store small amounts of data on the
client's computer.
• To set a cookie:
setcookie("user", "John", time() + (86400 * 30), "/"); // 30 days
To retrieve a cookie:
echo $_COOKIE["user"];
e) Explain any two string functions in PHP.
ans. • strlen() – Returns the length of a string.
Example: echo strlen("Hello"); // Output: 5
• strrev() – Reverses a string.
Example: echo strrev("Hello"); // Output: olleH
a)What are superglobals in PHP?
ans. Superglobals are built-in variables in PHP that are always
accessible, regardless of scope.
Examples:
• $_GET
• $_POST
• $_REQUEST
• $_SESSION
• $_COOKIE
• $_FILES
• $_SERVER
• $_ENV
• $_GLOBALS
b) Write the functions performed by a web browser.
Ans. • Sends requests to web servers using HTTP/HTTPS.
• Receives and renders HTML, CSS, JavaScript content.
• Interprets scripts and shows output to users.
• Manages cookies, sessions, and caches.
• Provides user interface for navigation and interaction.
c) Write a code in PHP which accepts two strings from user and
displays them after concatenation.
Ans. <form method="post">
Enter first string: <input type="text" name="str1"><br>
Enter second string: <input type="text" name="str2"><br>
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$s1 = $_POST['str1'];
$s2 = $_POST['str2'];
echo "Concatenated String: " . $s1 . " " . $s2;
}
?>
d) Write a PHP function to calculate factorial of a number using
recursion.
ans. function factorial($n) {
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
echo factorial(5); // Output: 120
e)Write a PHP program to print greatest number among given 3
numbers.
ans. $a = 10;
$b = 20;
$c = 15;
if ($a > $b && $a > $c) {
echo "$a is greatest";
} elseif ($b > $c) {
echo "$b is greatest";
} else {
echo "$c is greatest";
}
a)Explain self processing form using example.
ans. A self-processing form is a form where the same PHP file
handles both the form display and form processing. This is done
using $_SERVER['PHP_SELF'].
Example: <form method="post" action="<?php echo
$_SERVER['PHP_SELF']; ?>">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo "Hello, $name!";
}
?>
b)How inheritance is implemented in PHP? Explain using
example.
ans. Inheritance allows a class to use properties and methods of
another class using the extends keyword.
Example:
php
CopyEdit
class Animal {
public function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
public function sound() {
echo "Dog barks";
}
}
$dog = new Dog();
$dog->sound(); // Output: Dog barks
c)Write a menu driven program in PHP to display arithmaic
operations.
ans. $choice = 2;
$a = 10;
$b = 5;
switch($choice) {
case 1: echo "Addition: ".($a + $b); break;
case 2: echo "Subtraction: ".($a - $b); break;
case 3: echo "Multiplication: ".($a * $b); break;
case 4: echo "Division: ".($a / $b); break;
default: echo "Invalid choice";
}
d)Write a PHP program to generate random password.
Ans. function generatePassword($length = 8) {
$chars =
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX
YZ0123456789!@#$%^&*()';
return substr(str_shuffle($chars), 0, $length);
}
echo "Random Password: " . generatePassword();
e)Write a PHP program to create login page and welcome user on
next page.
ans. login.html
<form method="post" action="welcome.php">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
welcome.php
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin" && $pass == "1234") {
echo "Welcome, $user!";
} else {
echo "Invalid login.";
}
?>
a)What is Aray? Explain all types of array in-PHP.
Ans. Indexed Array – Array with numeric index
Associative Array – Array with named keys
Multidimensional Array – Array containing one or more
arrays
b) Explain the difference between while and do. .while loop in
PHP.
ans. while loop checks the condition first before executing.
// while
$i = 1;
while($i <= 5){
echo $i;
$i++;
}
do..while loop executes at least once before checking the
condition.
// do..while
$j = 1;
do{
echo $j;
$j++;
} while($j <= 5);
c)Write PHP program to check whether given number is
palindrome or not.
Ans. $num = 121;
$rev = strrev($num);
if ($num == $rev) {
echo "$num is a Palindrome";
} else {
echo "$num is not a Palindrome";
}
d) What is the difference between GET and POST Method.
• And. GET sends data via URL, visible to users.
• POST sends data hidden in request body.
• GET is suitable for small, non-sensitive data.
• POST is used for secure or large data transmission.
e) Explain passing value by reference with example.
Ans. Passing by reference means passing the actual variable, so
changes affect the original.
function addFive(&$num) {
$num += 5;
}
$a = 10;
addFive($a);
echo $a; // Output: 15
a) Explain relational operators in PHP.
Ans. Used to compare two values:
• == Equal
• != Not Equal
array.
• mysqli_close() – Closes connection.
Example:
$conn = mysqli_connect("localhost", "root", "", "testdb");
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
echo $row["username"] . "<br>";
}
mysqli_close($conn);
a) What is the difference between for and for each in PHP?
Ans. • for loop is used to iterate over a block of code a specific
number of times.
// for loop
for($i = 0; $i < 5; $i++) {
echo $i . " ";
}
• foreach loop is used to iterate over arrays.
// foreach loop
$arr = array("A", "B", "C");
foreach($arr as $val) {
echo $val . " ";
}
b) What is a session in PHP? Explain it.
Ans. A session is used to store information across multiple
pages (like user login info).
It uses a unique session ID stored in a cookie.
Example: session_start();
$_SESSION['username'] = "John";
echo $_SESSION['username'];
c) Write a PHP Script to display the total and percentage of
Marks of Subjects (Out of 100) Data Structure, Digital Marketing,
PHP, SE and Big data.
Ans. $data = 85;
$dm = 90;
$php = 88;
$se = 92;
$bd = 80;
$total = $data + $dm + $php + $se + $bd;
$percentage = ($total / 500) * 100;
echo "Total Marks: $total <br>";
echo "Percentage: $percentage%";
d) Explain cookies in PHP.
Ans. A cookie is a small file stored on the user's computer. It is
used to remember information (like login) between visits.
Example:
setcookie("user", "John", time()+3600); // expires in 1 hour
if(isset($_COOKIE["user"])) {
echo "Welcome " . $_COOKIE["user"];
}
e) Write a PHP Program to check whether Enter age from user is
allowed for vote or not.
Ans.
$age = 20;
if($age >= 18) {
echo "Eligible for voting";
} else {
echo "Not eligible for voting";
}
b) Explain if ______ then _________ else in PHP.
Ans.
if...else is used to make decisions in PHP.
Syntax: if(condition) {
// code if true
} else {
// code if false
}
Example:
$marks = 75;
if($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
c) What are data types of MySQL? Explain with example.
Ans. Common MySQL data types:
• INT – Integer values.
• VARCHAR(n) – Variable-length string.
• DATE – Date values.
Syntax:
// code to execute
Example:
<?php
function greet($name) {
echo "Hello, $name!";
}
greet("John");
?>
b) What is inheritance in PHP? Explain using example.
Ans. Inheritance is an OOP concept where one class (child)
derives properties and behaviors from another class (parent).
PHP supports single inheritance.
Example:
<?php
class Animal {
function sound() {
echo "Animal makes sound";
}
}
class Dog extends Animal {
function bark() {
echo "Dog barks";
}
}
$obj = new Dog();
$obj->sound(); // Inherited from Animal
$obj->bark(); // Defined in Dog
?>
c) Write a menu driven program in PHP to display arithmetic
operations.
Ans. <form method="post">
Enter Number 1: <input type="text" name="num1"><br>
Enter Number 2: <input type="text" name="num2"><br>
Operation:
<select name="op">
<option value="add">Add</option>
<option value="sub">Subtract</option>
<option value="mul">Multiply</option>
<option value="div">Divide</option>
</select><br>
<input type="submit" value="Calculate">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$a = $_POST["num1"];
$b = $_POST["num2"];
$op = $_POST["op"];
switch($op) {
case "add": echo "Sum: " . ($a + $b); break;
case "sub": echo "Difference: " . ($a - $b); break;
case "mul": echo "Product: " . ($a * $b); break;
case "div": echo "Quotient: " . ($a / $b); break;
default: echo "Invalid Operation";
}
}
?>
d) Write a program to illustrate sending email through PHP.
Ans. <?php
$to = "[email protected]";
$subject = "Test Mail";
$message = "This is a test email sent from PHP script.";
$headers = "From: [email protected]";
if(mail($to, $subject, $message, $headers)) {
echo "Email sent successfully!";
} else {
echo "Email sending failed.";
}
?>
e) Write a PHP program to print greatest number among given 3
numbers
Ans. <?php
$a = 45;
$b = 78;
$c = 66;
if($a >= $b && $a >= $c) {
echo "$a is the greatest.";
} elseif($b >= $a && $b >= $c) {
echo "$b is the greatest.";
} else {
echo "$c is the greatest.";
}
?>
a) What are the features of PHP.
Ans: •Open Source: PHP is free to use.
• Server-side Scripting: PHP runs on the server.
• Platform Independent: Works on Windows, Linux,
macOS, etc.
• Easy to Learn: Simple syntax similar to C.
• Database Support: Supports MySQL, PostgreSQL, etc.
• Embedded in HTML: PHP can be embedded in HTML
code.
• Large Community Support.
b) Write a PHP script to find the sum of digits of a number.
Ans. <?php
$num = 1234;
$sum = 0;
while($num > 0) {
$digit = $num % 10;
$sum += $digit;
$num = (int)($num / 10);
}
echo "Sum of digits: " . $sum;
?>
c) Explain for loop and foreach loop with example.
Ans. for loop is used when the number of iterations is known.
for($i=1; $i<=5; $i++) {
echo $i . " ";
}
foreach loop is used to iterate over arrays.
$colors = array("Red", "Green", "Blue");
foreach($colors as $color) {
echo $color . " ";
}
c) Explain cookies in PHP.
Ans. Cookies are used to store small data on the client's
browser.
Syntax: setcookie("user", "John", time() + 3600); // expires in 1
hour
To access:
echo $_COOKIE["user"];
d) Explain any two Built-in Array functions in PHP.
• array_sum($array) – Returns the sum of array elements.
• count($array) – Returns the number of elements in an
array.
a) Write a PHP script to display table of a number?
Ans. <?php
$num = 5;
echo "Table of $num:<br>";
for($i = 1; $i <= 10; $i++) {
echo "$num x $i = " . ($num * $i) . "<br>";
}
?>
b) Write any two Built-in functions of String with example.
Ans. •strlen() – Returns length of string
$str = "Hello";
echo strlen($str); // Output: 5
•strtoupper() – Converts string to uppercase
$str = "hello";
echo strtoupper($str); // Output: HELLO
c) Write a code in PHP which accepts two strings from user and
displays them after concatenation.
Ans. <form method="post">
String 1: <input type="text" name="str1"><br>
String 2: <input type="text" name="str2"><br>
<input type="submit" value="Concatenate">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$s1 = $_POST["str1"];
$s2 = $_POST["str2"];
echo "Concatenated String: " . $s1 . " " . $s2;
}
?>
d) Write a PHP program to calculate factorial of a number.
Ans. <?php
$num = 5;
$fact = 1;
for($i = 1; $i <= $num; $i++) {
$fact *= $i;
}
echo "Factorial of $num is: $fact";
?>
e) Write a PHP script to check whether a number is prime or not.
Ans. <?php
$num = 7;
$isPrime = true;
if ($num <= 1) $isPrime = false;
for($i = 2; $i <= sqrt($num); $i++) {
if ($num % $i == 0) {
$isPrime = false;
break;
}
}
echo $isPrime ? "$num is Prime" : "$num is not Prime";
?>
a) Explain the concept of sticky form with suitable example.
Ans. <form method="post">
Name: <input type="text" name="name" value="<?php
if(isset($_POST['name'])) echo $_POST['name']; ?>">
<input type="submit">
</form>
b) Explain Email id validation in PHP through regular expression.
Ans. $email = "[email protected]";
if (preg_match("/^[\w\.-]+@[\w\.-]+\.\w+$/", $email)) {
echo "Valid Email";
} else {
echo "Invalid Email";
}
c) Write PHP program for arsort() function.
And. <?php
$marks = array("John"=>75, "Mike"=>85, "Sara"=>70);
arsort($marks);
foreach($marks as $name => $mark) {
echo "$name = $mark<br>";
} ?>
d) Write a PHP program to display record of employee with
fields(empid,empname,salary,dept).
Ans. <?php
$employee = array("empid"=>101, "empname"=>"John",
"salary"=>50000, "dept"=>"IT");
foreach($employee as $key => $value) {
echo "$key : $value<br>";
}
?>
e) Write a PHP program to create login page and welcome user
on next page.
Ans. login.php
<form method="post" action="welcome.php">
Username: <input type="text" name="uname"><br>
Password: <input type="password" name="pass"><br>
<input type="submit" value="Login">
</form>
welcome.php
<?php
$uname = $_POST['uname'];
$pass = $_POST['pass'];
if($uname == "admin" && $pass == "1234") {
echo "Welcome, $uname!";
} else {
echo "Invalid credentials!";
}
?>
a) Explain multidimensional array in PHP with example.
Ans. A multidimensional array in PHP is an array containing one
or more arrays. These can be two-dimensional (arrays of arrays)
or more.
Example: <?php
$students = array(
array("John", 85, 90),
array("Alice", 78, 82),
array("Bob", 88, 79)
);
echo "Marks of " . $students[0][0] . ": Math = " . $students[0][1] .
", Science = " . $students[0][2];
?>
b) Write a PHP Program to check whether given year is leap year
or not (use if else)
Ans. <?php
$year = 2024;
if (($year % 4 == 0 && $year % 100 != 0) || ($year % 400 == 0)) {
echo "$year is a leap year.";
} else {
echo "$year is not a leap year.";
}
?>
c) Write a PHP script to define an interface which has methods
area () volume (). Define constant PI. Create a class cylinder
which implements this interface and calculate area and volume
Ans. <?php
interface Shape {
public function area();
public function volume();
}
define("PI", 3.14159);
class Cylinder implements Shape {
public $radius, $height;
public function __construct($r, $h) {
$this->radius = $r;
$this->height = $h;
}
public function area() {
return 2 * PI * $this->radius * ($this->radius + $this->height);
}
public function volume() {
return PI * pow($this->radius, 2) * $this->height;
}
}
$c = new Cylinder(5, 10);
echo "Area: " . $c->area();
echo "<br>Volume: " . $c->volume();
?>
d) What are the built in functions of string?
Ans. Some common string functions in PHP:
• strlen($str) – Returns length of a string.
• strrev($str) – Reverses a string.
• CREATE TABLE
CREATE TABLE users (id INT, name VARCHAR(50));
• INSERT
INSERT INTO users (id, name) VALUES (1, 'John');
• SELECT
SELECT * FROM users;
• UPDATE
• DELETE
DELETE FROM users WHERE id=1;