1. PHP Program to Check Leap 4.
PHP Program to Calculate
Year Factorial of a Number Using
<?php Recursion
$year = 2024; // The year to check <?php
function factorial($n) {
if (($year % 4 == 0 && $year % 100 // Base case: If n is 0, return 1
!= 0) || ($year % 400 == 0)) { if ($n == 0) {
echo "$year is a leap year."; return 1;
} else { } else {
echo "$year is not a leap year."; return $n * factorial($n - 1); //
} Recursive call
?> }
2. PHP Program to Reverse an }
Array echo factorial(5); // Outputs 120
<?php ?>
$array = [1, 2, 3, 4, 5]; // The
original array 5. PHP Program to Display the
$reversedArray = Total and Percentage of Marks of
array_reverse($array); // Reverse the Subjects
array <?php
print_r($reversedArray); // Print the $marks = [85, 90, 78, 88, 92]; //
reversed array Array of marks
?> $totalMarks = array_sum($marks); //
3. PHP Program to Display the Sum all the marks
Reverse of a String $maxMarks = 100; // Maximum
To reverse a string, we can use the marks per subject
PHP built-in function strrev(), which $totalSubjects = count($marks); //
takes a string and returns a new Number of subjects
string with its characters in reverse
order. Let's dive into the details: // Calculate percentage
php $percentage = ($totalMarks /
CopyEdit ($maxMarks * $totalSubjects)) *
<?php 100;
$string = "Hello, World!"; // Original echo "Total Marks:
string $totalMarks<br>"; // Display total
$reversedString = strrev($string); // marks
Reverse the string echo "Percentage: $percentage%"; //
echo $reversedString; // Display the Display percentage
reversed string ?>
?>
6. PHP Program to Find Sum of 8. PHP Program to Display
Digits of a Number Multiplication Table of Entered
<?php Value
$number = 12345; // The number to <?php
process $number = 5; // The number for
$sum = 0; // Variable to store the which the table is to be displayed
sum of digits
// Extract each digit and add to sum // Loop to display the multiplication
while ($number != 0) { table
$sum += $number % 10; // Add for ($i = 1; $i <= 10; $i++) {
the last digit of the number echo "$number x $i = " .
$number = (int)($number / 10); // ($number * $i) . "<br>"; // Multiply
Remove the last digit and display the result
} }
echo "Sum of digits: $sum"; // ?>
Display the sum of digits 9. PHP Program for Arithmetic
?> Operations Using Menu
<?php
7. PHP Program to Calculate Area $number1 = 10;
of Circle and Triangle $number2 = 5;
<?php $operation = '+';
// Area of Circle
$radius = 7; switch ($operation) {
$circleArea = pi() * pow($radius, 2); case '+':
// pi() returns the value of π, pow() echo $number1 + $number2;
calculates the square break;
// Area of Triangle case '-':
$base = 10; echo $number1 - $number2;
$height = 5; break;
$triangleArea = 0.5 * $base * case '*':
$height; // 0.5 * base * height echo $number1 * $number2;
echo "Area of Circle: break;
$circleArea<br>"; // Output circle case '/':
area echo $number1 / $number2;
echo "Area of Triangle: break;
$triangleArea"; // Output triangle default:
area echo "Invalid operation";
?> }
?>
10. PHP Program to Create a $number = 29; // The number to
Login Page and Welcome User check
<?php $isPrime = true;
// [Link]
if for ($i = 2; $i <= sqrt($number);
($_SERVER["REQUEST_METHO $i++) {
D"] == "POST") { if ($number % $i == 0) {
$username = $isPrime = false;
$_POST['username']; break;
$password = }
$_POST['password']; }
if ($username == "admin" && if ($isPrime) {
$password == "password") { echo "$number is a prime
echo "Welcome, $username!"; number.";
} else { } else {
echo "Invalid credentials."; echo "$number is not a prime
} number.";
} }
?> ?>
12. What is PHP?
<form method="post" PHP (Hypertext Preprocessor) is a
action="[Link]"> widely-used server-side scripting
Username: <input type="text" language that is particularly well-
name="username"><br> suited for web development.
Password: <input Initially, PHP stood for "Personal
type="password" Home Page," but as the language
name="password"><br> evolved, it came to represent "PHP:
<input type="submit" Hypertext Preprocessor," reflecting
value="Login"> its focus on web applications.
</form> Key Features of PHP:
11. PHP Program to Check 1. Server-Side Execution
Whether a Number is Prime 2. Embedded in HTML:
A prime number is a number 3. Database Integration:
greater than 1 that is divisible only 4. Cross-Platform:
by 1 and itself. Here's how to check 5. Open-Source:
for primality:
php
CopyEdit
<?php
13. What is the Difference print "Welcome to PHP!"; //
Between "echo" and "print"? Outputs: Welcome to PHP!
Both echo and print are used to 14. What are Different Types of
output data to the browser in PHP, Arrays in PHP?
but there are several important In PHP, arrays are variables that can
differences between them: hold multiple values. There are three
1. Basic Syntax and Use: primary types of arrays in PHP:
• echo: It is used to output one or 1. Indexed Arrays:
more strings. echo can output An indexed array uses numeric
multiple arguments, separated by indices to store and access values.
commas. The index is automatically assigned
echo "Hello, ", "World!"; // Outputs: by PHP, starting from 0 if not
Hello, World! explicitly specified.
• print: It is a language construct Example:
used to output a single string. <?php
Unlike echo, print can only take $fruits = array("Apple", "Banana",
one argument at a time. "Cherry");
print "Hello, World!"; // Outputs: echo $fruits[0]; // Outputs: Apple
Hello, World! ?>
2. Return Value: 2. Associative Arrays:
• echo: Does not return a value. It An associative array allows you to
is a statement, not a function. store data in key-value pairs, where
• print: Returns 1 so it can be used each key is associated with a
in expressions. specific value. This is useful when
$result = print "Hello"; // $result will you want to access values using
be 1 descriptive keys instead of numeric
4. Use Cases: indices.
• echo is more commonly used Example:
when you need to output multiple <?php
strings or complex HTML. $person = array("name" => "John",
• print is typically used when you "age" => 30, "city" => "New York");
need the expression to return a echo $person["name"]; // Outputs:
value (though this is less John
common in practice). ?>
Example: 3. Multidimensional Arrays:
// Using echo A multidimensional array is an array
echo "Welcome to ", "PHP of arrays, which can hold more
programming."; // Outputs: complex data structures like tables
Welcome to PHP programming. or matrices. These arrays allow you
// Using print to organize data in a hierarchy.
15. What is the Difference • GET: Typically used for
Between GET and POST retrieving data from the
Methods? server, such as search queries
In web development, GET and or navigation.
POST are two methods used to send • POST: Used for sending data
data to the server. They differ in to the server, such as form
several ways: submissions or file uploads.
1. Data Transmission: •
• GET: Sends data in the URL, 17. What Are Cookies in PHP?
which makes it visible to Cookies in PHP are small text files
anyone who views the URL. It that are stored on the client’s
is not suitable for sensitive browser to remember user
data. information. They are commonly
• POST: Sends data in the body used for tracking user sessions,
of the HTTP request, making remembering user preferences, or
it invisible in the URL. This is maintaining a shopping cart.
more secure and can handle How Cookies Work:
larger amounts of data. 1. Setting Cookies: Cookies are
2. Data Limitations: set using the setcookie()
• GET: The data sent through the GET function in PHP.
method is limited in length, as the URL 2. Retrieving Cookies: Once a
length is restricted by browsers and cookie is set, it can be
servers (usually up to 2048 characters). accessed on subsequent
• POST: There is no such restriction, and requests using the $_COOKIE
large amounts of data can be sent superglobal.
through the POST method. Example:
3. Security: php
• GET: Less secure, as data is CopyEdit
exposed in the URL. For // Set a cookie that expires in 1 hour
example, setcookie("user", "John", time() +
[Link] 3600);
=admin&password=12345
would expose sensitive // Access the cookie value
information. if (isset($_COOKIE['user'])) {
• POST: More secure, as data is echo "Welcome back, " .
not exposed in the URL and is $_COOKIE['user']; // Outputs:
sent in the body of the Welcome back, John
request. }
4. Use Cases:
16. What Are Superglobals in An associative array used to access
PHP? data stored in cookies. Cookies are
In PHP, superglobals are built-in small pieces of data stored on the
variables that are always accessible, user's computer.
regardless of scope. They are used to <?php
access information from various setcookie("user", "John", time() +
sources such as forms, cookies, 3600); // Set a cookie
sessions, and the server. The most echo $_COOKIE['user']; // Retrieve
common superglobals include: cookie value
1. $_GET: ?>
An associative array that collects 5. $_FILES:
data sent via the GET method in the An associative array used to handle
URL. It is used to retrieve query file uploads. It provides details about
string parameters. the uploaded file, such as its name,
<?php type, and size.
$name = $_GET['name']; <?php
echo "Hello, $name!"; if (isset($_FILES['file'])) {
?> echo $_FILES['file']['name']; //
2. $_POST: Display the name of the uploaded
An associative array that collects file
data sent via the POST method in a }
form submission. It is commonly ?>
used for form handling. 6. $_SERVER:
<?php An associative array containing
$name = $_POST['name']; information about the server
echo "Hello, $name!"; environment, such as headers, paths,
?> and script locations.
3. $_SESSION: <?php
An associative array used to store echo
session variables across multiple $_SERVER['SERVER_NAME']; //
pages. It is commonly used to Outputs the server's name
manage user login states. ?>
<?php 7. $_REQUEST:
session_start(); An associative array that combines
$_SESSION['user'] = 'admin'; // data from $_GET, $_POST, and
Store data in session $_COOKIE. It is commonly used
echo $_SESSION['user']; // Access when data can come from various
data from session sources.
?>
4. $_COOKIE:
18. What is a Session in PHP?
A session in PHP is a way to store // Access session variables
information (variables) to be used echo $_SESSION['user']; //
across multiple pages. Sessions are Outputs: John
used to persist data during a user’s echo $_SESSION['role']; // Outputs:
visit to a website. Unlike cookies, admin
which store data on the client side, Destroying a Session:
sessions store data on the server To destroy all session data, you can
side. use session_unset() and
session_destroy():
Key Features of Sessions: php
1. Session Start: A session must be CopyEdit
started at the beginning of each // Unset all session variables
page where session variables session_unset();
need to be accessed or set. This is
done using the session_start() // Destroy the session
function. session_destroy();
2. Unique Session ID: Each session
has a unique session ID, which is
sent to the user's browser via a When to Use Sessions:
cookie or URL parameter. This • User Authentication:
allows PHP to track the session Sessions are commonly used
across multiple requests. to store user login
3. Session Data Storage: All information.
session data is stored in the • Tracking User Activities:
$_SESSION superglobal array. You can track activities, such
4. Session Lifetime: Sessions as items in a shopping cart or
typically remain active until the user preferences, throughout
user closes the browser, or the the session.
session data is explicitly
destroyed.
Example:
php
CopyEdit
// Start the session
session_start();
// Set session variables
$_SESSION['user'] = 'John';
$_SESSION['role'] = 'admin';
19. What is Validation? 3. Length Validation: Check the
In the context of PHP, validation length of the input to make sure it
refers to the process of ensuring that falls within acceptable limits.
the input received from the user 4. Range Validation: Check that
(e.g., through forms) is correct and numerical values fall within an
secure before it is processed. acceptable range (e.g., age
Validation can help ensure that the between 18 and 100).
input matches expected formats, 20. What is the Purpose of the
such as email addresses, phone break Statement?
numbers, and passwords, and In PHP, the break statement is used
prevent issues such as SQL to exit from a loop or a switch
injection, cross-site scripting (XSS), statement. It allows you to terminate
and other security vulnerabilities. the current loop (such as for, while,
Types of Validation: foreach, etc.) before it has naturally
1. Client-Side Validation: This finished its execution. This is useful
occurs in the user's browser in cases where a specific condition is
before the data is sent to the met, and you no longer need to
server. It is typically done using continue iterating or checking.
JavaScript. While client-side Key Uses of the break Statement:
validation can enhance user 1. Breaking out of loops: The
experience by providing break statement will terminate
immediate feedback, it can be the loop immediately, regardless
bypassed, so it should not be of whether the loop has finished
relied upon alone. all iterations.
2. Server-Side Validation: This 2. Exiting a switch statement: In a
occurs on the server after the data switch statement, break prevents
has been sent. It is more secure, further cases from being executed
as it ensures the data is correct once a match is found.
before it is processed by the Example 1: Breaking out of a
server or stored in a database. Loop:
Common Validation Checks: <?php
1. Required Fields: Ensure that the for ($i = 0; $i < 10; $i++) {
user has filled in all necessary if ($i == 5) {
fields. break; // Exit the loop when $i
2. Format Validation: Check that is 5
the data matches specific patterns }
(e.g., valid email format, numeric echo $i . " ";
values for phone numbers). }
?>
Output: 0 1 2 3 4
21. Explain the array_slice() $array = array("apple", "banana",
Function in PHP "cherry", "date", "elderberry");
The array_slice() function in PHP is $slice = array_slice($array, 2, 3); //
used to extract a portion of an array. Start at index 2 and extract 3
This function does not modify the elements
original array but instead returns a print_r($slice);
new array that contains the selected ?>
elements. It is commonly used to Output:
work with subarrays, especially php
when you need to extract a segment CopyEdit
of the array based on a given offset Array
and length. (
Syntax: [0] => cherry
php [1] => date
CopyEdit [2] => elderberry
array_slice(array $array, int $offset, )
int $length = null, bool Example 2: Using Negative Offset
$preserve_keys = false): array php
• $array: The input array. CopyEdit
• $offset: The position to start <?php
extracting. If positive, it starts $array = array("apple", "banana",
from the beginning; if "cherry", "date", "elderberry");
negative, it starts from the end $slice = array_slice($array, -3, 2); //
of the array. Start 3 elements from the end,
• $length (optional): The extract 2 elements
number of elements to extract. print_r($slice);
If omitted, it will extract all ?>
elements from the offset to the Output:
end of the array. php
• $preserve_keys (optional): If CopyEdit
set to true, the original keys of Array
the array are preserved in the (
resulting array. If false (the [0] => cherry
default), the keys will be [1] => date
reindexed. )
Example 1: Basic Usage
php
CopyEdit
<?php
22. Explain the explode() Function [1] => banana
in PHP [2] => cherry
The explode() function in PHP is [3] => grape
used to split a string into an array )
based on a specified delimiter. This In this example, the string
is useful when you need to break a "apple,banana,cherry,grape" is split
string into parts, such as splitting a into an array of four elements based
sentence into words or processing on the comma delimiter.
CSV data. Example 2: Limiting the Number
Syntax: of Splits
php php
CopyEdit CopyEdit
explode(string $delimiter, string <?php
$string, int $limit = $string =
PHP_INT_MAX): array "apple,banana,cherry,grape";
• $delimiter: The boundary or $array = explode(",", $string, 3); //
character on which the string Only split into 3 parts
will be split. print_r($array);
• $string: The input string to be ?>
split. Output:
• $limit (optional): The php
maximum number of elements CopyEdit
in the resulting array. If Array
specified, the result will have (
a maximum number of splits. [0] => apple
Example 1: Basic Usage [1] => banana
php [2] => cherry,grape
CopyEdit )
<?php Here, the limit parameter is used to
$string = specify that the string should be split
"apple,banana,cherry,grape"; into at most 3 elements. The
$array = explode(",", $string); remaining part of the string
print_r($array); ("cherry,grape") is left as the third
?> element.
Output:
php
CopyEdit
Array
(
[0] => apple
23. Explain krsort() Function in 24. What is the Use of the
PHP $_SERVER Variable?
The krsort() function in PHP is used The $_SERVER superglobal is an
to sort an associative array in reverse associative array in PHP that
order, based on its keys. It is contains information about the
commonly used when you want to server environment and the current
sort an array by key in descending request. It provides access to various
order. server settings, headers, paths, and
Syntax: other information related to the
krsort(array &$array, int $sort_flags server and the HTTP request.
= SORT_REGULAR): bool Commonly Used $_SERVER
• $array: The input array to be Elements:
sorted. • $_SERVER['PHP_SELF']: The
• $sort_flags (optional): This filename of the currently
parameter can be used to modify executing script.
how the array is sorted. For • $_SERVER['SERVER_NAME'
example, SORT_NUMERIC can ]: The name of the server host
be used to sort the array under which the current script is
numerically. executing.
Example 1: Basic Usage • $_SERVER['REQUEST_MET
<?php HOD']: The request method used
$array = array("a" => "apple", "b" to access the page (e.g., GET,
=> "banana", "c" => "cherry"); POST).
krsort($array); • $_SERVER['HTTP_USER_AG
print_r($array); ENT']: The user agent string sent
?> by the browser, identifying the
Output: browser and operating system.
php • $_SERVER['REMOTE_ADDR
CopyEdit ']: The IP address from which the
Array user is viewing the current page.
( Example 1: Using
[c] => cherry $_SERVER['PHP_SELF']
[b] => banana <?php
[a] => apple echo "The current script is: " .
) $_SERVER['PHP_SELF'];
In this example, the associative array ?>
is sorted in reverse order by its keys. Output:
The current script is:
/path/to/current/[Link]
25. What Are Superglobals in echo "Age: " . $_GET['age']; //
PHP? Outputs: 30
Superglobals are built-in global ?>
arrays in PHP that can be accessed
from any part of the script, 26. What is the Difference
regardless of scope. They are Between echo and print in PHP?
predefined arrays and do not need to Both echo and print are language
be declared or initialized by the user. constructs used to output data to the
Common Superglobals: browser in PHP. However, they have
1. $_GET: Holds data sent via some subtle differences in behavior
the URL query string (GET and use cases.
method). Key Differences:
2. $_POST: Holds data sent via 1. Return Value:
the form submission (POST o echo: It does not return a
method). value. It simply outputs the
3. $_SESSION: Used to store data to the browser.
session variables. o print: It returns a value of 1,
4. $_COOKIE: Used to store which allows it to be used in
and retrieve cookies. expressions (e.g., if
5. $_FILES: Used for file (print("Hello"))).
uploads. 2. Performance:
6. $_REQUEST: A combination o echo is slightly faster than
of $_GET, $_POST, and print because it doesn’t return
$_COOKIE. a value.
7. $_SERVER: Contains server 3. Parameters:
and request information. o echo: It can take multiple
8. $_ENV: Holds environment parameters. For example, echo
variables. "Hello", " ", "World!"; is valid.
9. $_GLOBALS: A reference to o print: It can only take one
all global variables. argument at a time.
Example 1: Using $_GET Example 1: Using echo
php <?php
CopyEdit echo "Hello, World!"; // Outputs:
<?php Hello, World!
// Assuming the URL is echo "Hello", " ", "World!"; //
[Link] Outputs: Hello World!
=John&age=30 ?>
echo "Name: " . $_GET['name']; //
Outputs: John
27. What Are Different Types of );
Arrays in PHP? echo $people[0][0]; // Outputs: John
In PHP, arrays are used to store echo $people[1][1]; // Outputs: 30
multiple values in a single variable. Example of Mixed Arrays:
There are three main types of arrays: $mixedArray = array(
1. Indexed Arrays: 1 => "apple",
• Indexed arrays are arrays where "color" => "red",
the keys are automatically array(1, 2, 3)
assigned numeric indices starting );
from 0. You can also assign echo $mixedArray[0]; // Outputs:
custom indices, but by default, apple
PHP uses auto-indexing. echo $mixedArray["color"]; //
Example: 28. What Are Superglobals in
$fruits = array("apple", "banana", PHP?
"cherry"); Superglobals are built-in global
echo $fruits[0]; // Outputs: apple arrays in PHP that are automatically
echo $fruits[1]; // Outputs: banana accessible in all scopes throughout a
2. Associative Arrays: script. They store data about user
• Associative arrays use named input, server information, sessions,
keys that you assign to the cookies, and other global data.
values, rather than numeric Common Superglobals:
indices. This type of array is 1. $_GET: Stores data sent via the
useful when you need to URL query string (GET method).
associate specific labels with the o Example: $_GET['name']
values. retrieves the value of name
Example: passed in the URL
$age = array("John" => 25, "Jane" (?name=John).
=> 30, "Bob" => 35); 2. $_POST: Stores data sent via the
echo $age["John"]; // Outputs: 25 form submission (POST method).
3. Multidimensional Arrays: o Example: $_POST['email']
• Multidimensional arrays are retrieves the value of email sent
arrays that contain one or more through a form.
arrays. They are useful for 3. $_REQUEST: Stores data sent
storing complex data like tables by both $_GET and $_POST.
or matrices. o Example:
Example: $_REQUEST['username']
$people = array( retrieves data from either a GET
array("John", 25), or POST request.
array("Jane", 30), 4. $_SESSION:
array("Bob", 35)
29. What is the Purpose of the server. The key difference between
isset() Function in PHP? them lies in how the data is sent and
The isset() function in PHP is used how it can be accessed.
to check if a variable is set and is not GET Method:
null. It is commonly used to check if • Data is sent in the URL query
a variable has been initialized or if a string.
form input exists before processing • It is visible in the browser's
it. address bar.
Syntax: • It is used for retrieving data
php and should not be used for
CopyEdit sensitive or large amounts of
isset(mixed $var): bool data.
• $var: The variable to be • It has a limited data size (URL
checked. length limit).
• • Use Case: Search queries,
Example 1: Checking if a Variable links to resources.
is Set POST Method:
php • Data is sent in the body of the
CopyEdit request, not the URL.
<?php • It is not visible in the
$name = "John"; browser's address bar.
• It is used for sending large or
if (isset($name)) { sensitive data.
echo "Variable is set."; • It does not have a size limit
} else { like GET.
echo "Variable is not set."; • Use Case: Form submissions,
} file uploads, sensitive
?> information.
Output:
php
CopyEdit
Variable is set.
30. What is the Difference
Between GET and POST
Methods?
The GET and POST methods are
two HTTP request methods used to
send data from the client to the
31. What is a Cookie in PHP? } else {
A cookie is a small file stored on the echo "Hello, new visitor!";
client’s computer by the web }
browser at the request of a web ?>
server. Cookies are used to 32. What is a Session in PHP?
remember user-specific information A session in PHP is a way to store
like login details, preferences, cart user-specific information on the
contents, etc., across different pages server to be used across multiple
and visits. pages (e.g., after login, to maintain
How Cookies Work in PHP: user identity).
1. The server sends a cookie to the How Sessions Work:
client (browser) using the 1. A session ID is generated and
setcookie() function. stored in a cookie (or passed
2. The client stores it and sends it via URL).
back with every future request to 2. Server stores session variables
the same server. in a file or memory location
3. PHP accesses the cookie using associated with that ID.
the $_COOKIE superglobal. 3. PHP uses $_SESSION
Syntax: superglobal to store/retrieve
setcookie(name, value, expire, path, session data.
domain, secure, httponly); Starting a Session:
• name: The name of the cookie. session_start(); // Required at the
• value: The value to be stored. beginning of every session-using
• expire: The time the cookie page
expires (in UNIX timestamp). $_SESSION["username"] =
• path: The path on the server "JohnDoe";
where the cookie is available. Session vs Cookie:
• domain: The domain the cookie
Feature Cookie Session
is available to.
Client-side
• secure: If true, the cookie is only Storage Server-side
(Browser)
sent over HTTPS.
Security Less secure More secure
Example:
<?php Ends on
// Set a cookie for 1 hour Set browser
Expiry
setcookie("username", "JohnDoe", manually close or
time() + 3600); logout
if (isset($_COOKIE["username"])) { Size No major
~4 KB
echo "Welcome back, " . Limit limit
$_COOKIE["username"];
33. What is Validation in PHP? ?>
Validation is the process of ensuring
that form data entered by the user is <form method="post">
correct, complete, and secure Name: <input type="text"
before processing it. name="name">
Types of Validation: <input type="submit">
1. Client-Side Validation: </form>
Performed using HTML or 34. What is the Purpose of the
JavaScript before sending data break Statement in PHP?
to the server. The break statement in PHP is used
2. Server-Side Validation: to terminate a loop or switch-case
Done using PHP after form block prematurely before it naturally
submission—this is finishes execution.
mandatory even if client-side Where to Use break:
validation is used. • Inside for, while, or foreach
Why Validation is Important: loops.
• Prevents invalid or malicious • Inside switch statements to
data from being submitted. prevent fall-through.
• Ensures application stability Syntax:
and security. break; // Breaks the current
• Prevents SQL injection, XSS, loop
and other attacks. break 2; // Breaks two nested
Example of Server-Side loops
Validation: Example: Using break in a
<?php Loop
if <?php
($_SERVER["REQUEST_METHO for ($i = 1; $i <= 10; $i++) {
D"] == "POST") { if ($i == 5) {
$name = trim($_POST["name"]); break; // Exits loop when $i is
if (empty($name)) { 5
echo "Name is required."; }
} elseif (!preg_match("/^[a-zA-Z echo $i . " ";
]*$/", $name)) { }
echo "Only letters and spaces ?>
allowed."; Output:
} else { CopyEdit
echo "Name is valid: " . $name; 1234
}
}
35. Explain explode() Function in Output:
PHP Array
The explode() function in PHP is (
used to split a string into an array [0] => one
using a specific delimiter. [1] => two
Syntax: [2] => three,four,five
explode(separator, string, limit); )
• separator: The character or 36. Explain array_slice() Function
substring at which the string in PHP
will be split. The array_slice() function is used to
• string: The input string to be extract a portion of an array
split. without modifying the original array.
• limit (optional): Specifies the Syntax:
number of array elements to array_slice(array, offset, length,
return. preserve_keys);
Example: • array: The input array.
<?php • offset: Starting point in the array.
$text = "PHP is a powerful scripting • length (optional): How many
language"; elements to return.
$result = explode(" ", $text); // Split • preserve_keys (optional):
by space Whether to preserve keys (default
print_r($result); is false).
?> Example:
Output: <?php
Array $colors = ["red", "green", "blue",
( "yellow", "purple"];
[0] => PHP $subset = array_slice($colors, 1, 3);
[1] => is // From index 1 to 3 elements
[2] => a print_r($subset);
[3] => powerful ?>
[4] => scripting Output:
[5] => language php
) CopyEdit
Example with Limit: Array
<?php (
$text = "one,two,three,four,five"; [0] => green
$result = explode(",", $text, 3); [1] => blue
print_r($result); [2] => yellow
?> )
37. Explain krsort() Function in • arsort() → Sort array by value
PHP in descending order.
The krsort() function is used to sort 38. What is the Use of the
an associative array in descending $_SERVER Variable in PHP?
order according to key. The $_SERVER superglobal in PHP
Syntax: is an array containing information
php about headers, paths, and script
CopyEdit locations. It provides details about
krsort(array, sort_flags); the server and the current request.
• array: The array to be sorted. $_SERVER Elements:
• sort_flags: (Optional) Used to Descrip
Element
modify the sorting behavior. tion
Example: Filenam
php e of the
CopyEdit currentl
<?php $_SERVER['PHP_SELF']
y
$student_marks = ["John" => 85, executin
"Alice" => 90, "Bob" => 78]; g script
krsort($student_marks); Name of
print_r($student_marks); the
?> server
Output: $_SERVER['SERVER_N
host
php AME']
(e.g.,
CopyEdit localhos
Array t)
(
The
[John] => 85
request
[Bob] => 78
method
[Alice] => 90 $_SERVER['REQUEST_
used
) METHOD']
(e.g.,
Keys are sorted in reverse
GET,
(descending) alphabetical order.
POST)
Related Functions:
• ksort() → Sort array by key in
ascending order.
• asort() → Sort array by value
in ascending order,
maintaining index association.
39. What are Superglobals in Superglobal Description
PHP? request method,
Superglobals are a set of built-in script name).
global arrays in PHP that are always
Used for handling
accessible, regardless of scope.
$_FILES file uploads from an
These variables are available in all
HTML form.
scopes throughout a script, meaning
they can be accessed from any Stores session
function, class, or file without $_SESSION variables on the
needing to use the global keyword or server.
any special syntax. Stores data sent to
Why Are They Important? $_COOKIE the user's browser
Superglobals serve as a core and retrieved from it.
interface between user input, Stores environment
server settings, and application $_ENV variables passed to
logic. They are particularly useful in the current script.
form handling, session management, References all
cookie management, file uploads, $_GLOBALS variables available in
and accessing server information. the global scope.
Common Superglobals in Example:
PHP: php
Superglobal Description CopyEdit
Used to collect data <?php
sent via the HTTP echo "Page URL: " .
$_GET $_SERVER['PHP_SELF'] . "<br>";
GET method (URL
query parameters). echo "Name from GET: " .
Used to collect data $_GET['name'] . "<br>";
sent via the HTTP ?>
$_POST If the URL is
POST method (form
submissions). [Link]/[Link]?name=John,
it outputs:
Contains both
pgsql
$_GET and $_POST
$_REQUEST CopyEdit
data along with
Page URL: /[Link]
$_COOKIE.
Name from GET: John
Contains server and
$_SERVER environment-related
information (e.g.,
40. What is the Difference CopyEdit
Between GET and POST <form method="GET"
Methods? action="[Link]">
The GET and POST methods are <input type="text"
two commonly used HTTP request name="username">
methods in HTML forms. Though <input type="submit"
they serve a similar purpose — to value="Submit via GET">
send data from a client to the server </form>
— they differ significantly in how
they do so. <form method="POST"
GET Method: action="[Link]">
• Sends form data appended to the <input type="text"
URL as query parameters. name="username">
• It is visible in the browser <input type="submit"
address bar (e.g., value="Submit via POST">
[Link]/[Link]?name=Jo </form>
hn). Comparison Table:
• Limited to a maximum of 2048 Feature GET POST
characters depending on the
Data
browser. Appends
hidden in
• Suitable for non-sensitive data Visibility data in
HTTP
like search queries or filters. URL
body
• Data sent via GET can be
bookmarked and cached. Less More
Security
secure secure
POST Method:
• Sends data inside the HTTP Limited
request body, not visible in the size (about No size
Data Limit
URL. 2048 limitation
• No data length limitations (larger chars)
payloads allowed). Can be Cannot be
Bookmarki
• More secure for sensitive data bookmark bookmark
ng
such as passwords or personal ed ed
information. Login,
• Cannot be bookmarked directly Search, form
or cached. Use Case
filters submissio
• Commonly used for login forms, ns
registrations, and file uploads.
Code Example:
html