0% found this document useful (0 votes)
49 views

PHP Programming-1

PHP

Uploaded by

ddugkyhr1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

PHP Programming-1

PHP

Uploaded by

ddugkyhr1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

DEPARTMENT OF COMPUTER SCIENCE (AI&DS),IT

II B.Sc – PHP PROGRAMMING


PAPER CODE: 23UADSE04
STUDY MATERIAL

2024-2025
INTERNAL & EXTERNAL MARKS PATTERN
Theory –Marks Distribution

Maximum Marks : 100 Marks


External [EA] : 75
Marks Internal [CIA] : 25
Theory - Question Paper Pattern [External] (Total Marks: 75)
PART – A (15 x 1 = 15 Marks)
(Answer ALL questions),

PART – B (2 x 5 = 10 Marks)
(Answer ANY TWO questions)
&
(Open Choice – 2 out of 5 questions)

PART – C(5 x 10 = 50 Marks)


(Answer ALL questions)
&
(One question from each unit with Internal Choice)

Theory - Internal Marks Distribution (Total Marks: 25)


Attendance: 5 Marks
Assignment: 5 Marks
Test : 15 Marks
UNIT- I
Introduction to PHP -Basic Knowledge of websites
Introduction of Dynamic Website -Introduction to PHP -Scope
of PHP -XAMPP and WAMP Installation
UNIT- II
PHP Programming Basics -Syntax of PHP -Embedding PHP in HTML -Embedding HTML in PHP.
Introduction to PHP Variable -Understanding Data Types Using Operators -Using Conditional Statements -If(),
else if()
and else if condition Statement.
UNIT- III
Switch() Statements -Using the while() Loop -Using the for()
Loop PHP Functions.
PHP Functions -Creating an Array -Modifying Array Elements -Processing Arrays with Loops - Grouping Form
Selections with Arrays -Using Array Functions.
UNIT -IV
PHP Advanced Concepts -Reading and Writing Files -Reading Data from a File. 6

UNIT- V
Managing Sessions and Using Session Variables -Destroying a
Session -Storing Data in Cookies -Setting Cookies.
UNIT -I
What is PHP?
PHP is an acronym for (PHP: Hypertext Preprocessor) is a widely-used open source
general-purpose scripting language that is especially suited for web development and can be
embedded into HTML.
• PHP scripts are executed on the server.
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
• PHP code are executed on the server, and the result is returned to the browser as plain
HTML.
• PHP files have extension ".php".
What Can PHP Do?
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also
output any text, such as XHTML and XML.

Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.).
• PHP is compatible with almost all servers used today (Apache, IIS, etc.).
• PHP supports a wide range of databases.
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side.
• PHP is widely-used.
How Does PHP Work?
As Previously mentioned that PHP is a server-side programming language which means it runs
in the server. PHP plays an intermediate role between a client and the date stored in the server
and other servers.
What Do You Need to Start Using PHP?
• Install a web server
• Install PHP
• Install a database, such as MySQL
You can install a server on your personal computer such as XAMPP server from the link below:
https://www.apachefriends.org/index.html
A PHP version and MySQL come out of the box when you install XAMPP server. You can use
other development server instead of XAMPP such as WAMPSERVER that you can download
from here (http://www.wampserver.com/en/).

PHP Syntax:

A PHP script is executed on the server, and the plain HTML result is sent back to the browser.

➢ Basic PHP Syntax:


• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>
Ex:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>

Note: PHP statements end with a semicolon (;).

➢ Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
Ex:
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/

➢ PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.

In the example below, all three echo statements below are legal (and equal):
Ex:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";

?>
</body>
</html>

However; all variable names are case-sensitive.


In the example below, only the first statement will display the value of the $color variable (this
is because $color, $COLOR, and $coLOR are treated as three different variables)
Ex:
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";

?>

PHP Variables:
• Start with a $
• Contain only letters, numbers, and the underscore
• The first character after the $ cannot be a number
• Are case-sensitive
• Use a consistent naming scheme!
Ex:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
➢ PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes:
• local
• global
• static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed
outside a function:
Ex:
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>

A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
Ex:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";

?>
• PHP The global Keyword
The global keyword is used to access a global variable from within a function. To
do this, use the global keyword before the variables (inside the function):

Ex:
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;

$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>

• PHP The static Keyword


Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a
further job.
To do this, use the static keyword when you first declare the variable:
Ex:
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>

Then, each time the function is called, that variable will still have the information it
contained from the last time the function was called.
Note: The variable is still local to the function.
PHP Data Types
Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

➢ PHP String
A string can be any text inside quotes. You can use single or double quotes:
Ex:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;

echo "<br>";
echo $y;

?>
You can use either quotation mark type to create the string.
To use a variable within another string, you must use double quotation marks.
Ex:
$first_name = 'Tobias';

$today = 'August 2, 2011';


$var = "Define \"platitude\", please.";
$var = 'Define "platitude", please.';
echo $first_name;
echo "Hello, $first_name";
➢ PHP Integer
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative
• Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based
- prefixed with 0x) or octal (8-based - prefixed with 0)

In the following example $x is an integer. The PHP var_dump() function returns the data
type and value:

Ex:
<?php
$x = 5985;
var_dump($x);
?>

➢ PHP Float
float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type
and value:
Ex:
<?php
$x = 10.365;
var_dump($x);
?>

➢ PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
Ex:
$x = true;
$y = false;
➢ PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data
type and value:
Ex:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);

?>
➢ PHP Object
An object is a data type which stores data and information on how to process that data.
In PHP, an object must be explicitly declared.
First we must declare a class of object. For this, we use the class keyword. A class is a
structure that can contain properties and methods:
Ex:
<?php
class Car {
function Car() {
$this->model = "VW";
}
}
$herbie = new Car(); // create an object
echo $herbie->model; // show object properties
?>

➢ PHP NULL Value


• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• Tip: If a variable is created without a value, it is automatically assigned a value of
NULL.
• Variables can also be emptied by setting the value to NULL:
Ex:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);

?>

➢ PHP Resource
• The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP.
• A common example of using the resource data type is a database call.
• We will not talk about the resource type here, since it is an advanced topic

-Basic Knowledge of websites

A website is a collection of many web pages, and web pages are digital files that are written using
HTML(HyperText Markup Language). To make your website available to every person in the
world, it must be stored or hosted on a computer connected to the Internet round a clock. Such
computers are known as a Web Server.
The website’s web pages are linked with hyperlinks and hypertext and share a common interface
and design. The website might also contain some additional documents and files such as images,
videos, or other digital assets.

With the Internet invading every sphere, we see websites for all kinds of causes and purposes. So,
we can also say that a website can also be thought of as a digital environment capable of
delivering information and solutions and promoting interaction between people, places, and things
to support the goals of the organization it was created for.
Components of a Website: We know that a website is a collection of a webpages hosted on a
web-server. These are the components for making a website.
Webhost: Hosting is the location where the website is physically located. Group of webpages
(linked webpages) licensed to be called a website only when the webpage is hosted on the
webserver. The webserver is a set of files transmitted to user computers when they specify the
website’s address..
Address: Address of a website also known as the URL of a website. When a user wants to open a
website then they need to put the address or URL of the website into the web browser, and the
asked website is delivered by the webserver.
Homepage : Home page is a very common and important part of a webpage. It is the first
webpage that appears when a visitor visits the website. The home page of a website is very
important as it sets the look and feel of the website and directs viewers to the rest of the pages on
the website.
Design : It is the final and overall look and feel of the website that has a result of proper use and
integration elements like navigation menus, graphics, layout, navigation menus etc.
Content : Every web pages contained on the website together make up the content of the website.
Good content on the webpages makes the website more effective and attractive.
The Navigation Structure: The navigation structure of a website is the order of the pages, the
collection of what links to what. Usually, it is held together by at least one navigation menu.
How to access Websites?
When we type a certain URL in a browser search bar, the browser requests the page from the Web
server and the Web server returns the required web page and its content to the browser. Now, it
differs from how the server returns the information required in the case of static and dynamic
websites.

Types of Website:

Static Website
Dynamic Website
Static Website: In Static Websites, Web pages are returned by the server which are prebuilt
source code files built using simple languages such as HTML, CSS, or JavaScript. There is no
processing of content on the server (according to the user) in Static Websites. Web pages are
returned by the server with no change therefore, static Websites are fast. There is no interaction
with databases. Also, they are less costly as the host does not need to support server-side
processing with different languages.
Dynamic Website: In Dynamic Websites, Web pages are returned by the server which is
processed during runtime means they are not prebuilt web pages, but they are built during runtime
according to the user’s demand with the help of server-side scripting languages such as PHP,
Node.js, ASP.NET and many more supported by the server. So, they are slower than static
websites but updates and interaction with databases are possible. Dynamic Websites are used over
Static Websites as updates can be done very easily as compared to static websites (Where altering
in every page is required) but in Dynamic Websites, it is possible to do a common change once,
and it will reflect in all the web pages.

There are different types of websites on the whole internet, we had chosen some most common
categories to give you a brief idea –
Blogs: These types of websites are managed by an individual or a small group of persons, they
can cover any topics — they can give you fashion tips, music tips, travel tips, fitness tips.
Nowadays professional blogging has become an external popular way of earning money online.
E-commerce: These websites are well known as online shops. These websites allow us to make
purchasing products and online payments for products and services. Stores can be handled as
standalone websites.
Portfolio: These types of websites acts as an extension of a freelancer resume. It provides a
convenient way for potential clients to view your work while also allowing you to expand on your
skills or services.
Brochure: These types of websites are mainly used by small businesses, these types of websites
act as a digital business card, and used to display contact information, and to advertise services,
with just a few pages.
News and Magazines: These websites needs less explanation, the main purpose of these types of
websites is to keep their readers up-to-date from current affairs whereas magazines focus on the
entertainment.
Social Media: We all know about some famous social media websites like Facebook, Twitter,
Reddit, and many more. These websites are usually created to let people share their thoughts,
images, videos, and other useful components.
Educational: Educational websites are quite simple to understand as their name itself explains it.
These websites are designed to display information via audio or videos or images.
Portal: These types of websites are used for internal purposes within the school, institute, or any
business, These websites often contain a login process allowing students to access their credential
information or allows employees to access their emails and alerts.
Dynamic Websites
Dynamic Website is a website containing data that can be mutable or changeable. It uses client-
side or server scripting to generate mutable content. Like a static website, it also contains HTML
data.
Dynamic websites are those websites that changes the content or layout with every request to the
webserver. These websites have the capability of producing different content for different visitors
from the same source code file. There are two kinds of dynamic web pages i.e. client side
scripting and server side scripting. The client-side web pages changes according to your activity
on the web page. On the server-side, web pages are changed whenever a web page is loaded.
Example: login & signup pages, application & submission forms, inquiry and shopping cart
pages.
A Typical Architecture of dynamic website

There are different languages used to create dynamic web pages like PHP, ASP, .NET and JSP.
Whenever a dynamic page loads in browser, it requests the database to give information
depending upon user’s input. On receiving information from the database, the resulting web page
is applied to the user after applying the styling codes.
Features of dynamic webpage:
• These websites are very flexible.
• In these websites the content can be quickly changed on the user’s computer without new
page request to the web browser.
• In these websites the owner have the ability to simply update and add new content to the
site.
• These websites are featured with content management system, e-commerce system and
intranet or extranet facilities.
• Most of the dynamic web content, is assembled on the web using server-scripting
languages.
Advantages of dynamic webpage:
• It provides more functional websites.
• It is very easy to update.
• It helps in the search engines because new content brings people back to the site.
• These are interactive websites because these can be customized.
• These websites can work as a system to allow staff or users to collaborate.
• It’s easy to modify or update data.
• It provides a user-friendly interactive interface for users.
• proves smooth navigation.
• provide interactive user interface
• It provides a better user experience.
• It provides real-time data.
Disadvantages of dynamic webpages:
• These types of websites are complex.
• These are more expensive to develop.
• Hosting of these websites is also costlier.
• It requires a rapid, high-end web server.
• high production costs.
• Slow to load content.
• Client will require a skilled programmer to build a dynamic website.
• Hosting a website is costly as compared to a dynamic website.
• Low speed compared to a static website
Application Of Dynamic Website:
Here is a list of application where we use dynamic website over static website
• Online booking system:
• E-commerce website.
• Voting or polls,
• Forums
• E-newsletter.

Real-life application:
Here is a list of application where we use dynamic website in real world.
• Facebook
• Twitter
• LinkedIn
• Online booking website.
• Social media

Scope of PHP:
PHP (Hypertext Preprocessor) is a popular server-side scripting language that is primarily used
for web development. Its scope includes:
1. Web Development: PHP is widely used for building dynamic websites and web
applications. It works well with databases (especially MySQL) to generate dynamic
content.
2. Content Management Systems (CMS): Many popular CMS platforms like WordPress,
Joomla, and Drupal are built using PHP, which has contributed to its widespread use.
3. E-commerce: PHP powers many e-commerce platforms like Magento, OpenCart, and
WooCommerce (WordPress plugin).
4. Server-Side Scripting: PHP runs on a web server, making it useful for tasks like handling
form data, user authentication, and session management.
5. Database Integration: PHP integrates easily with databases like MySQL, PostgreSQL,
and SQLite, making it a go-to language for building data-driven web applications.
6. APIs and Web Services: PHP can be used to build RESTful APIs and web services,
allowing communication between different systems over HTTP.
7. Automation and Scripting: PHP can also be used for writing scripts to automate tasks like
data processing, backups, and email handling.
XAMPP and WAMP Installation
Both XAMPP and WAMP are software packages that provide a local development
environment for PHP and MySQL. They include everything you need to run a PHP-based web
application on your computer.
1. Installing XAMPP:
XAMPP is a free, open-source platform that includes Apache, MySQL, PHP, and Perl. Here’s
how to install it:
1. Download XAMPP: Go to the official XAMPP website and download the version of
XAMPP suitable for your operating system (Windows, macOS, or Linux).
2. Run the Installer: After downloading the installer, run it to begin the installation process.
3. Choose Components: You can choose which components you want to install (Apache,
MySQL, PHP, etc.). The default settings work fine for most users.
4. Choose Installation Directory: Select where you want to install XAMPP. The default
directory is usually C:\xampp on Windows.

5. Start XAMPP: After installation is complete, launch the XAMPP Control Panel. Start the
Apache and MySQL services by clicking the "Start" buttons next to each.
6. Test the Installation: Open your browser and go to http://localhost. If the XAMPP
welcome page appears, the installation was successful.

2. Installing WAMP:
WAMP is another local server environment for Windows that includes Apache, MySQL, and
PHP. Here's how to install it:
1. Download WAMP: Visit the official WAMP server website and download the latest
version.
2. Run the Installer: Once the installer is downloaded, run it and follow the on-screen
instructions.
3. Select Installation Directory: Choose the folder where you want WAMP to be installed
(default is C:\wamp).
4. Choose Components: WAMP comes with Apache, MySQL, PHP, and a few other tools.
The default components are usually fine.
5. Configure the Default Browser: During installation, you may be prompted to choose your
default browser (you can leave this as it is if you use the default browser).
6. Start WAMP: Once installed, launch the WAMP Manager. The WAMP icon in the
system tray will turn green when everything is running correctly.
7. Test the Installation: Open your browser and go to http://localhost. If the WAMP server
page shows up, the installation was successful.
Key Differences Between XAMPP and WAMP:
1. Operating System:
o XAMPP is cross-platform, available for Windows, Linux, and macOS.
o WAMP is designed specifically for Windows.

2. Components:
o XAMPP includes additional components like Perl and Mercury Mail Server.
o WAMP focuses mainly on Apache, MySQL, and PHP.
3. Interface:
o XAMPP uses a control panel for managing services.
o WAMP uses a system tray icon for managing the server.
4. Popularity:
o XAMPP is more widely used across different platforms, especially for PHP
developers working on cross-platform projects.
o WAMP is primarily used by developers working on Windows environments

MCQ
1. What does PHP stand for?
• A) Personal Home Page
• B) Predefined Hypertext Processor
• C) Personal Hypertext Processor
• D) Hypertext Preprocessor
Answer: D) Hypertext Preprocessor
2. PHP is mainly used for:
• A) Desktop applications
• B) Web development
• C) Mobile app development
• D) Game development
Answer: B) Web development
3. Which of the following is a correct PHP syntax for outputting "Hello World"?
• A) echo "Hello World";
• B) print("Hello World");
• C) output("Hello World");
• D) Both A and B
Answer: D) Both A and B
4. Which PHP function is used to get the length of a string?
• A) strlen()
• B) strlength()
• C) stringlen()
• D) length()
Answer: A) strlen()
5. Which of the following is NOT a valid PHP variable name?
• A) $var_name
• B) $VarName
• C) $_varName
• D) var_name$
Answer: D) var_name$
6. What does HTML stand for?
• A) Hyper Text Markup Language
• B) Hyper Tool Marking Language
• C) Hypertext Transfer Language
• D) Home Tool Marking Language
Answer: A) Hyper Text Markup Language
7. Which of the following is used to create a website?
• A) HTML
• B) CSS
• C) JavaScript
• D) All of the above
Answer: D) All of the above

8. Which HTML tag is used to display a hyperlink?


• A) <link>
• B) <a>
• C) <hyperlink>
• D) <href>
Answer: B) <a>
9. Which of the following is used to style HTML pages?
• A) HTML
• B) CSS
• C) JavaScript
• D) PHP
Answer: B) CSS
10. Which tag is used to display an image in HTML?
• A) <image>
• B) <img>
• C) <picture>
• D) <src>
Answer: B) <img>
11. A dynamic website is:
• A) A website with static content
• B) A website that does not change after loading
• C) A website with content that changes based on user interaction
• D) A website with no images or videos
Answer: C) A website with content that changes based on user interaction
12. Which of the following is used to create a dynamic web page?
• A) HTML
• B) CSS
• C) PHP
• D) JavaScript
Answer: C) PHP
13. Dynamic websites rely heavily on:
• A) Server-side scripting
• B) Client-side scripting
• C) Only HTML
• D) Only CSS
Answer: A) Server-side scripting
14. Which is an example of a dynamic website?
• A) Wikipedia
• B) Static portfolio website
• C) An image gallery with no database
• D) A webpage with no user interaction
Answer: A) Wikipedia
15. Which of the following is NOT a dynamic website feature?
• A) User authentication
• B) Real-time updates
• C) Static text content
• D) User-submitted forms
Answer: C) Static text content
16. PHP scripts are executed on the:
• A) Client-side
• B) Server-side
• C) Browser
• D) User’s computer
Answer: B) Server-side
17. Which PHP function is used to get the current date?
• A) getDate()
• B) currentDate()
• C) date()
• D) current_time()
Answer: C) date()
18. Which of the following is a correct PHP array syntax?
• A) $arr = (1, 2, 3);
• B) $arr = [1, 2, 3];
• C) $arr = {1, 2, 3};
• D) $arr = (1=>2, 3=>4);
Answer: B) $arr = [1, 2, 3];
19. What is the correct way to comment a single line in PHP?
• A) # This is a comment
• B) // This is a comment
• C) <!-- This is a comment -->
• D) Both A and B
Answer: D) Both A and B
20. What is the main purpose of PHP sessions?
• A) To store data on the client-side
• B) To store user data across multiple pages
• C) To run PHP code in the background
• D) To store data in a database
Answer: B) To store user data across multiple pages
21. Which of the following is an advantage of PHP?
• A) It is easy to learn.
• B) It is platform-independent.
• C) It supports a wide range of databases.
• D) All of the above
Answer: D) All of the above
22. PHP can be embedded directly into:
• A) HTML
• B) CSS
• C) JavaScript
• D) None of the above
Answer: A) HTML
23. Which of the following is NOT a valid use of PHP?
• A) Building static websites
• B) Sending emails
• C) Working with databases
• D) Creating content management systems
Answer: A) Building static websites

24. Which function in PHP is used to open a file?


• A) fopen()
• B) openfile()
• C) fileopen()
• D) fileopen()
Answer: A) fopen()

25. PHP can be used to interact with:


• A) MySQL
• B) PostgreSQL
• C) SQLite
• D) All of the above
Answer: D) All of the above
26. XAMPP stands for:
• A) X-AMP for PHP
• B) Cross-platform Apache, MySQL, PHP, Perl
• C) X-AMP for PHP, MySQL
• D) XAMP - Apache MySQL PHP
Answer: B) Cross-platform Apache, MySQL, PHP, Perl
27. Which of the following services does XAMPP provide?
• A) Apache Server
• B) MySQL Database
• C) FileZilla FTP Server
• D) All of the above
Answer: D) All of the above
28. Which PHP version is supported by XAMPP?
• A) PHP 5.x
• B) PHP 7.x
• C) PHP 8.x
• D) All of the above
Answer: D) All of the above
29. Which of the following is NOT included in WAMP?
• A) Apache
• B) MySQL
• C) PHP
• D) PostgreSQL
Answer: D) PostgreSQL
30. What is the main difference between XAMPP and WAMP?
• A) XAMPP is for Windows only, and WAMP is cross-platform.
• B) WAMP is for Windows only, and XAMPP is cross-platform.
• C) XAMPP has MySQL, and WAMP uses PostgreSQL.
• D) There is no difference.
Answer: B) WAMP is for Windows only, and XAMPP is cross-platform.
31. After installing XAMPP, to check if the server is running, which URL should be entered
in the browser?
• A) http://localhost
• B) http://localhost/phpmyadmin
• C) http://127.0.0.1
• D) All of the above
Answer: D) All of the above
32. Which control panel should you use to start Apache and MySQL in XAMPP?
• A) XAMPP Control Panel
• B) WAMP Server Control Panel
• C) Task Manager
• D) System Preferences
Answer: A) XAMPP Control Panel
33. Which command can you use to check the status of Apache in XAMPP?
• A) apache -status
• B) apache2 status
• C) httpd -status
• D) It shows status automatically on the control panel
Answer: D) It shows status automatically on the control panel
34. Which file in XAMPP is used to configure the Apache server?
• A) httpd.conf
• B) apache.conf
• C) xampp.conf
• D) config.php
Answer: A) httpd.conf
35. What is the default location for the root directory in XAMPP?
• A) C:\xampp\htdocs
• B) C:\wamp\www
• C) C:\xampp\www
• D) C:\xampp\html
Answer: A) C:\xampp\htdocs
36. What is WAMP's default root directory?
• A) C:\xampp\htdocs
• B) C:\wamp\www
• C) C:\wamp\htdocs
• D) C:\wamp\www
Answer: B) C:\wamp\www

37. Which service is NOT included in WAMP by default?


• A) MySQL
• B) PHP
• C) Apache
• D) FileZilla FTP Server
Answer: D) FileZilla FTP Server
38. Which of the following is true about PHP running on XAMPP/WAMP?
• A) PHP code is executed on the client-side.
• B) PHP runs only in a web browser.
• C) PHP is interpreted on the server-side.
• D) PHP needs no server to run.
Answer: C) PHP is interpreted on the server-side.
39. What is the default port for Apache in XAMPP?
• A) 8080
• B) 80
• C) 3306
• D) 443
Answer: B) 80
40. Which of the following is NOT an installation requirement for XAMPP?
• A) Apache
• B) PHP
• C) MySQL
• D) IIS
Answer: D) IIS
41. Which version of PHP does XAMPP support?
• A) PHP 4.x
• B) PHP 5.x
• C) PHP 7.x
• D) PHP 8.x
Answer: C) PHP 7.x
42. Which language is primarily used for backend web development in XAMPP/WAMP?
• A) JavaScript
• B) HTML
• C) PHP
• D) Python
Answer: C) PHP
43. Which server is used in WAMP for serving PHP files?
• A) Apache
• B) IIS
• C) Nginx
• D) Tomcat
Answer: A) Apache
44. What is the primary role of MySQL in XAMPP/WAMP?
• A) To handle server-side scripts
• B) To store and manage data in a database
• C) To compile PHP code
• D) To serve static files
Answer: B) To store and manage data in a database
45. What does PHP stand for?
• A) Predefined Hypertext Processor
• B) Hypertext Preprocessor
• C) Personal Home Page
• D) Hyperlink Preprocessor
Answer: B) Hypertext Preprocessor
46. Which of the following is true about XAMPP?
• A) It works only on Windows
• B) It supports multiple operating systems
• C) It only supports Apache server
• D) It does not support PHP
Answer: B) It supports multiple operating systems
47. What is the default web root directory for PHP files in XAMPP?
• A) C:\xampp\www
• B) C:\xampp\htdocs
• C) C:\wamp\www
• D) C:\wamp\htdocs
Answer: B) C:\xampp\htdocs
48. What is PHP commonly used for?
• A) Front-end development
• B) Back-end development
• C) Graphics designing
• D) Database management
Answer: B) Back-end development
49. Which of the following tools is used to manage databases in XAMPP?
• A) phpMyAdmin
• B) MySQL Workbench
• C) SQL Server Management Studio
• D) None of the above
Answer: A) phpMyAdmin

50. Which software package provides a local development environment for PHP?
• A) WAMP
• B) XAMPP
• C) Both A and B
• D) Neither A nor B
Answer: C) Both A and B
5 MARKS

1. Explain the role of PHP in web development and its basic syntax with an example.
2. Describe the difference between static and dynamic websites with examples.
3. What is PHP, and how does it integrate with HTML to create dynamic web pages?
4. Explain the key advantages of using PHP for web development over other server-side
languages.
5. What are the common features and functions of a dynamic website?
6. Discuss the scope of PHP in modern web development and its integration with databases.
7. What are the key differences between XAMPP and WAMP for local PHP development?
8. Describe the process of installing XAMPP and configuring it to run PHP scripts locally.
9. How does PHP handle form data submitted from a web page? Provide an example.
10.Explain the concept of PHP sessions and their use in maintaining user state across pages.
11.What is the role of MySQL in conjunction with PHP, and how can you connect to a
MySQL database using PHP?
12.How does the echo statement in PHP work, and what are its common uses in web
development?
13.Describe the steps to install and configure WAMP for local web development and running
PHP.
10 MARKS

1. Explain the basic features and benefits of PHP in web development, with examples of
common PHP functions.
2. Describe the differences between static and dynamic websites, and explain how PHP is
used to create dynamic websites.
3. What is the role of PHP in building dynamic websites, and how does it interact with
HTML, CSS, and JavaScript?
4. Discuss the scope of PHP in modern web development, including its usage in content
management systems, e-commerce, and web applications.
5. Explain the installation process of XAMPP and WAMP, and compare their features and
suitability for different web development needs.
6. Describe how to establish a connection between PHP and a MySQL database, and
demonstrate basic operations like INSERT, UPDATE, and SELECT.
7. What are PHP sessions and cookies, and how are they used for maintaining user state and
preferences across multiple web pages?
8. Explain the concept of error handling in PHP using try, catch, and finally, and provide
examples of catching different types of exceptions.
9. Discuss the process of debugging PHP scripts, including common errors and how tools like
XAMPP and WAMP can assist in the development process.
UNIT- II
PHP Syntax

PHP, a powerful server-side scripting language used in web


development. It’s simplicity and ease of use makes it an ideal choice for
beginners and experienced developers. This article provides an overview
of PHP syntax. PHP scripts can be written anywhere in the document
within PHP tags along with normal HTML.
Basic PHP Syntax
PHP code is executed between PHP tags, allowing the integration of
PHP code within HTML. The most common PHP tag is <?php … ?>,
which is used to enclose PHP code. The <?php ….?> is called Escaping
to PHP.
PHP
<?php
// code
?>
The script starts with <?php and ends with ?>. These tags are also called
‘Canonical PHP tags’. Everything outside of a pair of opening and
closing tags is ignored by the PHP parser. The open and closing tags are
called delimiters. Every PHP command ends with a semi-colon (;).
Basic Example of PHP
PHP
<?php

// Here echo command is used to print


echo "Hello, world!";

?>

Output
Hello, world!
Embedding PHP in HTML
PHP code can be embedded within HTML using the standard PHP tags.
In this example, the <?php echo “Hello, PHP!”; ?> statement
dynamically inserts a heading into the HTML document.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Syntax Example</title>
</head>
<body>
<h1><?php echo "Hello, PHP!"; ?></h1>
</body>
</html>
SGML or Short HTML Tags
These are the shortest option to initialize a PHP code. The script starts
with <? and ends with ?>. This will only work by setting
the short_open_tag setting in the php.ini file to ‘on’.
Example:
PHP
<?

// Here echo command will only work if


// setting is done as said before
echo "Hello, world!";

?>

Output
Hello, world!
Case Sensitivity
PHP is partially case-sensitive-
• Keywords (like if, else, while, echo) are not case-sensitive.
• Variable names are case-sensitive.
Example:
PHP
<?php

$Var = "Hello Geeks";

// Outputs: Hello Geeks


echo $Var;

// Error: Undefined variable $variable


echo $var;

?>
Comments in PHP
Comments are used to make code more readable by explaining the
purpose of specific code blocks. Comments are ignored by the PHP
interpreter.
1. Single Line Comment
As the name suggests, these are single line or short relevant explanations
that one can add to their code. To add this, we need to begin the line
with (//) or (#).
PHP
<?php

// This is a single line comment


// These cannot be extended to more lines

echo "Hello World!";

# This is also a single line comment

?>

Output
Hello World!

Output:

hello world!!!
2. Multi-Line or Multiple Line Comment
It is used to accommodate multiple lines with a single tag and can be
extended to many lines as required by the user. To add this, we need to
begin and end the line with (/*…*/)

PHP
<?php

/* This is a multi line comment


In PHP variables are written
by adding a $ sign at the
beginning.*/

$geek = "Hello World!";


echo $geek;

?>

Output
Hello World!
Variables and Data Types
Variables are used to store data that can be manipulated within PHP.
They are declared using the $ symbol followed by the variable name.
Declaring Variables
Variables are created by assigning a value to them using the assignment
operator (=).
PHP
$name = "XYZ"; // String
$age = 30; // Integer
$isEmployed = true; // Boolean
Data Types
PHP supports several data types, including:
• String: A sequence of characters.
• Integer: Whole numbers.
• Float (Double): Numbers with a decimal point.
• Boolean: Represents true or false.
• Array: A collection of values.
• Object: An instance of a class.
• NULL: A special type representing a variable with no value.
• Resource: A special type that holds a reference to external resources
(like database connections).
Blocks in PHP
In PHP, multiple statements can be executed simultaneously (under a
single condition or loop) by using curly-braces ({}). This forms a block
of statements that gets executed simultaneously.
PHP
<?php

$var = 50;

if ($var>0){
echo ("Positive as \n");
echo ("greater than 0");
}

?>

Output
Positive as
greater than 0
How to embed PHP code in an HTML page ?
PHP is the abbreviation of Hypertext Preprocessor and earlier it was
abbreviated as Personal Home Page.
We can use PHP in HTML code by simply adding a PHP tag without
doing any extra work.
Example 1: First open the file in any editor and then write HTML code
according to requirement. If we have to add PHP code then we can add
by simply adding <?php ….. ?> tags in between and add your PHP code
accordingly.
• PHP
<!DOCTYPE html>
<html>
<head>
<title>PHP</title>
</head>
<body>
<h1>
<?php
echo "hii GeeksforGeeks "
?>
</h1>
</body>
</html>
Output:

Example 2: In this, we can use PHP code in different lines so that we


can make a webpage according to the need and put code wherever
necessary as shown in the below example
• PHP
<html>

<body>
<h2>Welcome to GeeksforGeeks</h2>
<?php
echo "Good morning";
?>

<p>Good to see you</p>

<?php
$str = "This is GeeksforGeeks portal";
echo " $str.";
?>
</body>
</html>
Output:

Example 3: In this, we use PHP code in HTML document using


the post method where we can pass value in HTML form and receive in
the PHP post method.
• PHP
<html>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$str = $_POST['fname'];
if (empty($str))
{
echo "String is empty";
}
else
{
?>
<h1>
<?php echo $str ?>
</h1>
<?php
}
}
?>
</body>
</html>
Output:

PHP Variables

PHP Variables are one of the most fundamental concepts in


programming. It is used to store data that can be accessed and
manipulated within your code. Variables in PHP are easy to use,
dynamically typed (meaning that you do not need to declare their type
explicitly), and essential for creating dynamic, interactive web
applications.
Declaring Variables in PHP
To declare a variable in PHP, you simply assign a value to it using the $
symbol followed by the variable name. PHP variables are case-sensitive
and must start with a letter or an underscore, followed by any number of
letters, numbers, or underscores.
Example
PHP
<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>
Variable Naming Conventions
In PHP, it’s important to follow certain naming conventions for PHP
variables to ensure readability and maintainability:
• Start with a Letter or Underscore: Variable names must begin with a
letter or an underscore (_), not a number.
• Use Descriptive Names: Variable names should be descriptive of their
purpose, e.g., $userName, $totalAmount.
• Case Sensitivity: PHP variable names are case-sensitive, meaning $name
and $Name are different variables.
• Avoid Reserved Words: Do not use PHP reserved words or keywords as
variable names (e.g., function, class, echo).
Example of Valid and Invalid Variable Names
PHP
<?php

$firstName = "Alice"; // Valid


$_age = 25; // Valid

$2ndPlace = "Bob"; // Invalid: Cannot start with a number


$class = "Physics"; // Valid, but avoid reserved words

?>
Data Types in PHP
• Integers: Integers are whole numbers without decimals, which can be
positive or negative.
• Doubles: Floats are numbers with decimal points or in exponential form.
• NULL: The NULL data type represents a variable with no value.
• Strings: Strings are sequences of characters, enclosed in single (‘ ‘) or
double (” “) quotes.
• Booleans: Booleans represent two possible values: true or false.
• Arrays: Arrays are used to store multiple values in a single variable.
Arrays can be indexed, associative, or multidimensional.
• Objects: Objects are instances of classes, which are templates for
creating data structures with properties and methods.
• Resources: Resources are special variables that hold references to
external resources, such as database connections or file handles.
PHP Variable Scope
The scope of a variable refers to where it can be accessed within the
code. PHP variables can have local, global, static, or superglobal scope.
1. Local Scope or Local Variable
Variables declared within a function have local scope and cannot be
accessed outside the function. Any declaration of a variable outside the
function with the same name (as within the function) is a completely
different variable.
Example: This example shows the local variable in PHP.
PHP
<?php

$num = 60;

function local_var() {

// This $num is local to this function

// The variable $num outside the function


// is a completely different
$num = 50;
echo "Variable num inside function is: $num \n";
}

local_var();

// The $num outside function is a completely


// different from inside local_var()
echo "Variable num outside function is: $num";

?>

Output
Variable num inside function is: 50
Variable num outside function is: 60
2. Global Scope or Global Variable
The variables declared outside a function are called global variables.
These variables can be accessed directly outside a function. To get
access within a function we need to use the “global” keyword before the
variable to refer to the global variable.
Example: This example shows the Global Variables in PHP.
PHP
<?php
$num = 20;

// Function to demonstrate use of global variable


function global_var() {

// We have to use global keyword before


// the variable $num to access within
// the function
global $num;

echo "Variable num inside function: $num \n";


}

global_var();

echo "Variable num outside function: $num \n";

?>

Output
Variable num inside function: 20
Variable num outside function: 20
3. Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its
execution and the memory is freed. But sometimes we need to store the
variables even after the completion of function execution. To do this, we
use the static keywords and the variables are then called static
variables. PHP associates a data type depending on the value for the
variable.
Example: This example shows the Static variable in PHP.
PHP
<?php

// Function to demonstrate static variables


function static_var() {

// Static Variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";


echo $sum, "\n";
}

// First function call


static_var();

// Second function call


static_var();

?>

Output
6
3
7
3
Note: You must have noticed that $num regularly increments even after
the first function call but $sum doesn’t. This is because $sum is not
static, and its memory is freed after the execution of the first function
call.
4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from
anywhere in the script, including within functions. Common
superglobals include $_GET, $_POST, $_SESSION, $_COOKIE,
$_SERVER, and $_GLOBALS.
PHP
<?php

// Using $_SERVER superglobal to


// get server information
echo $_SERVER['SERVER_NAME'];
?>
Variable Variables
• PHP allows us to use dynamic variable names, called variable variables.
• Variable variables are simply variables whose names are dynamically
created by another variable’s value.
Example: This example shows the declaration of a variable by the use
of the another variable.
PHP
<?php
$a = 'hello'; //hello is value of variable $a
$$a = 'World'; //$($a) is equals to $(hello)
echo $hello; //$hello is World i.e. $hello is new variable with value
'World'
?>

Output
World

PHP Data Types


PHP data types are a fundamental concept to defines how variables store
and manipulate data. PHP is a loosely typed language, which means
variables do not need to be declared with a specific data type. PHP
allows eight different types of data types. All of them are discussed
below.
Table of Content
• Predefined Data Types
o Integer
o Float (Double)
o String
o Boolean
• User-Defined (compound) Data Types
o Array
o Objects
• Special Data Types
o NULL
o Resources
Predefined Data Types
1. Integer
Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point. They can
be decimal (base 10), octal (base 8), or hexadecimal (base 16). The
default base is decimal (base 10). The octal integers can be declared with
leading 0 and the hexadecimal can be declared with leading 0x. The
range of integers must lie between -2^31 to 2^31.
PHP
<?php

// decimal base integers


$deci1 = 50;
$deci2 = 654;

// octal base integers


$octal1 = 07;

// hexadecimal base integers


$octal = 0x45;

$sum = $deci1 + $deci2;


echo $sum;
echo "\n\n";

//returns data type and value


var_dump($sum)

?>

Output
704

int(704)
2. Float (Double)
Can hold numbers containing fractional or decimal parts including
positive and negative numbers or a number in exponential form. By
default, the variables add a minimum number of decimal places. The
Double data type is the same as a float as floating-point numbers or real
numbers.
PHP
<?php

$val1 = 50.85;
$val2 = 654.26;

$sum = $val1 + $val2;

echo $sum;
echo "\n\n";

//returns data type and value


var_dump($sum)

?>
Output
705.11

float(705.11)
3. String
Hold letters or any alphabets, even numbers are included. These are
written within double quotes during declaration. The strings can also be
written within single quotes, but they will be treated differently while
printing variables. To clarify this look at the example below.
PHP
<?php

$name = "Krishna";
echo "The name of the Geek is $name \n";
echo 'The name of the geek is $name ';
echo "\n\n";

//returns data type, size and value


var_dump($name)

?>

Output
The name of the Geek is Krishna
The name of the geek is $name

string(7) "Krishna"
4. Boolean
Boolean data types are used in conditional testing. Hold only two values,
either TRUE(1) or FALSE(0). Successful events will return true and
unsuccessful events return false. NULL type values are also treated
as false in Boolean. Apart from NULL, 0 is also considered false in
boolean. If a string is empty then it is also considered false in boolean
data type.
PHP
<?php

if(TRUE)
echo "This condition is TRUE";
if(FALSE)
echo "This condition is not TRUE";
?>

Output
This condition is TRUE
User-Defined (compound) Data Types
1. Array
Array is a compound data type that can store multiple values of the same
data type. Below is an example of an array of integers. It combines a
series of data that are related together.
PHP
<?php

$intArray = array( 10, 20 , 30);

echo "First Element: $intArray[0]\n";


echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n\n";

//returns data type and value


var_dump($intArray);

?>

Output
First Element: 10
Second Element: 20
Third Element: 30

array(3) {
[0]=>
int(10)
[1]=>
int(20)
[2]=>
int(30)
}
We will discuss arrays in detail in further articles.
2. Objects
Objects are defined as instances of user-defined classes that can hold
both values and functions and information for data processing specific to
the class. This is an advanced topic and will be discussed in detail in
further articles. When the objects are created, they inherit all the
properties and behaviours from the class, having different values for all
the properties.
Objects are explicitly declared and created from the new keyword.
PHP
<?php

class gfg {
public $message;

function __construct($message) {
$this->message = $message;
}

function msg() {
return "This is an example of " . $this->message . "!";
}
}

$newObj = new gfg("Object Data Type");


echo $newObj->msg();

?>

Output
This is an example of Object Data Type!
Special Data Types
1. NULL
These are special types of variables that can hold only one value i.e.,
NULL. We follow the convention of writing it in capital form, but it’s
case-insensitive NULL, Null, and null are treated the same. If a variable
is created without a value or no value, it is automatically assigned a
value of NULL. It is written in capital letters.
PHP
<?php

$nm = NULL;
echo $nm; // this will return no output

// return data type


var_dump($nm);
?>

Output
NULL

2. Resources
Resources in PHP are not an exact data type. These are basically used to
store references to some function call or to external PHP resources. For
example, consider a database call. This is an external resource. Resource
variables hold special handles for files and database connections.

PHP Operators
Operators are used to performing operations on some values.

PHP provides us with many operators to perform such operations on


various operands or variables, or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are
the various groups of operators:
• Arithmetic Operators
• Logical or Relational Operators
• Comparison Operators
• Conditional or Ternary Operators
• Assignment Operators
• Spaceship Operators (Introduced in PHP 7)
• Array Operators
• Increment/Decrement Operators
• String Operators
Let us now learn about each of these operators in detail.
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical
operations like addition, subtraction, multiplication, etc. Below is the list
of arithmetic operators along with their syntax and operations in PHP.
Operato Synta
r Name x Operation

$x + Sum the
+ Addition
$y operands

Difference
$x –
– Subtraction s the
$y
operands
Operato Synta
r Name x Operation

Product of
$x *
* Multiplication the
$y
operands

The
$x / quotient of
/ Division
$y the
operands

$x raised
Exponentiatio $x **
** to the
n $y
power $y

The
$x % remainder
% Modulus
$y of the
operands
Note: The exponentiation has been introduced in PHP 5.6.
Example: This example explains the arithmetic operator in PHP.
PHP
<?php
// Define two numbers
$x = 10;
$y = 3;

// Addition
echo "Addition: " . ($x + $y) . "\n";

// Subtraction
echo "Subtraction: " . ($x - $y) . "\n";

// Multiplication
echo "Multiplication: " . ($x * $y) . "\n";

// Division
echo "Division: " . ($x / $y) . "\n";
// Exponentiation
echo "Exponentiation: " . ($x ** $y) . "\n";

// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>

Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
Logical or Relational Operators:
These are basically used to operate with conditional statements and
expressions. Conditional statements are based on conditions. Also, a
condition can either be met or cannot be met so the result of a
conditional statement can either be true or false. Here are the logical
operators along with their syntax and operations in PHP.
Operator Name Syntax Operation

True if both the


Logical $x and
and operands are
AND $y
true else false

True if either of
Logical $x or
or the operands is
OR $y
true else false

True if either of
Logical $x xor the operands is
xor
XOR $y true and false if
both are true

True if both the


Logical $x &&
&& operands are
AND $y
true else false

|| Logical $x || $y True if either of


Operator Name Syntax Operation

OR the operands is
true else false

Logical True if $x is
! !$x
NOT false
Example: This example describes the logical & relational operator in
PHP.
PHP
<?php
$x = 50;
$y = 30;
if ($x == 50 and $y == 30)
echo "and Success \n";

if ($x == 50 or $y == 20)
echo "or Success \n";

if ($x == 50 xor $y == 20)


echo "xor Success \n";

if ($x == 50 && $y == 30)


echo "&& Success \n";

if ($x == 50 || $y == 20)
echo "|| Success \n";

if (!$z)
echo "! Success \n";
?>
Output:
and Success
or Success
xor Success
&& Success
|| Success
! Success
Comparison Operators: These operators are used to compare two
elements and outputs the result in boolean form. Here are the
comparison operators along with their syntax and operations in PHP.
Operator Name Syntax Operation

Returns True
$x == if both the
== Equal To
$y operands are
equal

Returns True
Not $x != if both the
!=
Equal To $y operands are
not equal

Returns True
Not $x <> if both the
<>
Equal To $y operands are
unequal

Returns True
if both the
$x === operands are
=== Identical
$y equal and are
of the same
type

Returns True
if both the
Not $x == operands are
!==
Identical $y unequal and
are of
different types

Returns True
Less $x <
< if $x is less
Than $y
than $y

Returns True
Greater $x >
> if $x is greater
Than $y
than $y
Operator Name Syntax Operation

Returns True
Less
$x <= if $x is less
<= Than or
$y than or equal
Equal To
to $y

Returns True
Greater
$x >= if $x is greater
>= Than or
$y than or equal
Equal To
to $y
Example: This example describes the comparison operator in PHP.
PHP
<?php
$a = 80;
$b = 50;
$c = "80";

// Here var_dump function has been used to


// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
Conditional or Ternary Operators:
These operators are used to compare two values and take either of the
results simultaneously, depending on whether the outcome is TRUE or
FALSE. These are also used as a shorthand notation
for if…else statement that we will read in the article on decision making.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either evaluate as true or false. If the condition
evaluates to True, then value1 will be assigned to the variable $var
otherwise value2 will be assigned to it.
Operator Name Operation

If the condition is true? then $x :


or else $y. This means that if the
?: Ternary condition is true then the left
result of the colon is accepted
otherwise the result is on right.
Example: This example describes the Conditional or Ternary operators
in PHP.
PHP
<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Output:
The number is negative
Assignment Operators: These operators are used to assign values to
different variables, with or without mid-operations. Here are the
assignment operators along with their syntax and operations, that PHP
provides for the operations.
Operator Name Syntax Operation

Operand on
the left
$x = obtains the
= Assign
$y value of the
operand on
the right
Operator Name Syntax Operation

Simple
Add then $x += Addition
+=
Assign $y same as $x
= $x + $y

Simple
Subtract $x -= subtraction
-=
then Assign $y same as $x
= $x – $y

Simple
Multiply $x *= product
*=
then Assign $y same as $x
= $x * $y

Simple
Divide then
$x /= division
/= Assign
$y same as $x
(quotient)
= $x / $y

Simple
Divide then
$x %= division
%= Assign
$y same as $x
(remainder)
= $x % $y
Example: This example describes the assignment operator in PHP.
PHP
<?php
// Simple assign operator
$y = 75;
echo $y, "\n";

// Add then assign operator


$y = 100;
$y += 200;
echo $y, "\n";

// Subtract then assign operator


$y = 70;
$y -= 10;
echo $y, "\n";

// Multiply then assign operator


$y = 30;
$y *= 20;
echo $y, "\n";

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";

// Divide then assign(remainder) operator


$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0
Array Operators: These operators are used in the case of arrays. Here
are the array operators along with their syntax and operations, that PHP
provides for the array operation.
Operator Name Syntax Operation

$x + Union of both
+ Union
$y i.e., $x and $y

Returns true
$x == if both has
== Equality
$y same key-
value pair

$x != Returns True
!= Inequality
$y if both are
Operator Name Syntax Operation

unequal

Returns True
if both have
the same key-
$x ===
=== Identity value pair in
$y
the same
order and of
the same type

Returns True
Non- $x !== if both are not
!==
Identity $y identical to
each other

Returns True
$x <>
<> Inequality if both are
$y
unequal
Example: This example describes the array operation in PHP.
PHP
<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");

var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
Increment/Decrement Operators: These are called the unary operators
as they work on single operands. These are used to increment or
decrement values.
Operator Name Syntax Operation

First
increments
Pre-
++ ++$x $x by one,
Increment
then return
$x

First
decrements
Pre-
— –$x $x by one,
Decrement
then return
$x

First returns
Post- $x, then
++ $x++
Increment increment it
by one

First returns
Post- $x, then
— $x–
Decrement decrement it
by one
Example: This example describes the Increment/Decrement operators in
PHP.
PHP
<?php
$x = 2;
echo ++$x, " First increments then prints \n";
echo $x, "\n";

$x = 2;
echo $x++, " First prints then increments \n";
echo $x, "\n";

$x = 2;
echo --$x, " First decrements then prints \n";
echo $x, "\n";

$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:
3 First increments then prints
3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1
String Operators: This operator is used for the concatenation of 2 or
more strings using the concatenation operator (‘.’). We can also use the
concatenating assignment operator (‘.=’) to append the argument on the
right side to the argument on the left side.
Operato Synta
r Name x Operation

Concatenatio Concatenate
. $x.$y
n d $x and $y

First
concatenate
Concatenatio
$x.=$ s then
.= n and
y assigns,
assignment
same as $x
= $x.$y
Example: This example describes the string operator in PHP.
PHP
<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
GeeksforGeeks!!!
GeeksforGeeks!!!
Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator.
The spaceship operator or combined comparison operator is denoted by
“<=>“. These operators are used to compare values but instead of
returning the boolean results, it returns integer values. If both the
operands are equal, it returns 0. If the right operand is greater, it returns -
1. If the left operand is greater, it returns 1. The following table shows
how it works in detail:
Operator Syntax Operation

$x <=>
$x < $y Identical to -1 (right is greater)
$y

$x <=>
$x > $y Identical to 1 (left is greater)
$y

Identical to -1 (right is greater)


$x <= $x <=>
or identical to 0 (if both are
$y $y
equal)

Identical to 1 (if left is greater)


$x >= $x <=>
or identical to 0 (if both are
$y $y
equal)

$x == $x <=>
Identical to 0 (both are equal)
$y $y
Operator Syntax Operation

$x <=>
$x != $y Not Identical to 0
$y
Example: This example illustrates the use of the spaceship operator in
PHP.
PHP
<?php
$x = 50;
$y = 50;
$z = 25;

echo $x <=> $y;


echo "\n";

echo $x <=> $z;


echo "\n";

echo $z <=> $y;


echo "\n";

// We can do the same for Strings


$x = "Ram";
$y = "Krishna";

echo $x <=> $y;


echo "\n";

echo $x <=> $y;


echo "\n";

echo $y <=> $x;


?>
Output:
0
1
-1
1
1
-1
Conditional Statement in PHP
A conditional statement in PHP is a programming construct that allows
you to execute different blocks of code based on whether a specified
condition evaluates to true or false. It enables you to create dynamic and
flexible code logic by controlling the flow of execution based on various
conditions.
Conditional statements in PHP include:
PHP conditional statements, like if, else, elseif, and switch, control code
execution based on specified conditions, enhancing code flexibility and
logic flow.
if statement:
PHP if statement executes a block of code if a specified condition is true.
if (condition) {
// Code to execute if condition is true
}
else statement:
PHP else statement executes a block of code if the condition of the
preceding if statement evaluates to false.
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
else if statement:
PHP else if statement allows you to evaluate multiple conditions
sequentially and execute the corresponding block of code if any
condition is true.
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if both condition1 and condition2 are false
}
switch statement:
PHP switch statement provides an alternative to multiple elseif
statements by allowing you to test a variable against multiple possible
values and execute different blocks of code accordingly.
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases can be added as needed
default:
// Code to execute if expression doesn't match any case
}

MCQ
1. What is the correct way to declare a PHP variable?
o a) var name;
o b) name = "John";
o c) $name = "John";
o d) name := "John";
o Answer: c) $name = "John";
2. Which of the following is the correct way to embed PHP code within
an HTML file?
o a) <script>PHP code</script>
o b) <php>PHP code</php>
o c) <?php PHP code ?>
o d) <?php] PHP code [?>
o Answer: c) <?php PHP code ?>
3. Which symbol is used to denote a PHP variable?
o a) @
o b) #
o c) $
o d) &
o Answer: c) $
4. What will be the output of the following PHP code?
php
Copy code
$x = 5;
$y = 10;
echo $x + $y;
o a) 510
o b) 15
o c) 5 + 10
o d) 5 10
o Answer: b) 15
5. What is the purpose of the echo statement in PHP?
o a) To define a variable
o b) To output text to the browser
o c) To perform a calculation
o d) To accept user input
o Answer: b) To output text to the browser
6. Which of the following is used to end a PHP statement?
o a) .
o b) ;
o c) :
o d) ,
o Answer: b) ;
7. What is the correct way to write a comment in PHP?
o a) /* This is a comment */
o b) // This is a comment
o c) # This is a comment
o d) All of the above
o Answer: d) All of the above
8. How can you check if a PHP script is being processed in a web
browser?
o a) Using print()
o b) Using echo
o c) Using exit()
o d) Using print_r()
o Answer: b) Using echo
9. Which of the following will work to declare a constant in PHP?
o a) define('PI', 3.14);
o b) constant('PI', 3.14);
o c) constant PI = 3.14;
o d) var PI = 3.14;
o Answer: a) define('PI', 3.14);
10.Which PHP function is used to include a PHP file in another PHP
file?
o a) include()
o b) require()
o c) include_once()
o d) All of the above
o Answer: d) All of the above
11.What will the following PHP code output?
php
Copy code
echo "<h1>Hello World</h1>";
o a) Hello World
o b) <h1>Hello World</h1>
o c) Hello World as an H1 tag
o d) None of the above
o Answer: c) Hello World as an H1 tag
12.How do you display the value of a PHP variable inside an HTML
tag?
o a) <?php echo $variable ?>
o b) <php echo $variable ?>
o c) <?php $variable ?>
o d) <?php var $variable ?>
o Answer: a) <?php echo $variable ?>
13.Which of the following is the correct syntax for embedding HTML in
PHP?
o a) <?php <h1>Heading</h1> ?>
o b) <?php echo "<h1>Heading</h1>"; ?>
o c) <?php echo '<h1>Heading</h1>'; ?>
o d) Both b and c are correct
o Answer: d) Both b and c are correct
14.Which of the following is a valid variable name in PHP?
o a) 2name
o b) _name
o c) @name
o d) #name
o Answer: b) _name
15.What will be the output of the following code?
php
Copy code
$x = 10;
echo $x;
o a) 10
o b) $x
o c) Error
o d) None of the above
o Answer: a) 10
16.Which PHP data type is used to store true or false values?
o a) String
o b) Integer
o c) Boolean
o d) Object
o Answer: c) Boolean
17.Which function is used to get the type of a variable in PHP?
o a) gettype()
o b) type()
o c) var_type()
o d) typeof()
o Answer: a) gettype()
18.Which of the following is not a valid data type in PHP?
o a) Integer
o b) String
o c) Object
o d) Floaty
o Answer: d) Floaty
19.Which data type in PHP is used to store decimal values?
o a) Integer
o b) String
o c) Float
o d) Boolean
o Answer: c) Float
20.What will the following code output?
php
Copy code
$x = "Hello";
$y = 5;
echo $x . $y;
o a) Hello5
o b) Hello 5
o c) Hello
o d) 5
o Answer: a) Hello5

21.Which operator is used for string concatenation in PHP?


o a) .
o b) +
o c) ,
o d) &
o Answer: a) .
22.What is the output of the following expression?
php
Copy code
$x = 10;
$y = 5;
echo $x / $y;
o a) 5
o b) 2
o c) 10
o d) 15
o Answer: a) 5
23.Which of the following is the correct way to increment a variable by
1 in PHP?
o a) $x++
o b) ++$x
o c) $x += 1
o d) All of the above
o Answer: d) All of the above
24.Which of the following PHP operators is used to compare two values
for equality?
o a) =
o b) ==
o c) ===
o d) !=
o Answer: b) ==
25.What does the !== operator do in PHP?
o a) Compares if two values are not equal
o b) Compares if two values and types are not equal
o c) Compares if two values are equal
o d) Compares if two values are the same
o Answer: b) Compares if two values and types are not equal
26.What is the output of the following expression?
php
Copy code
$x = 7;
$y = 3;
echo $x % $y;
o a) 1
o b) 0
o c) 3
o d) 7
o Answer: a) 1
27.Which of the following is the correct syntax for an if statement in
PHP?
o a) if $x > 5 { echo "True"; }
o b) if (x > 5) { echo "True"; }
o c) if ($x > 5) { echo "True"; }
o d) if ($x > 5) then echo "True";
o Answer: c) if ($x > 5) { echo "True"; }
28.What will the following PHP code output?
php
Copy code
$x = 10;
if ($x > 5) {
echo "Greater";
} else {
echo "Lesser";
}
o a) Greater
o b) Lesser
o c) Error
o d) No output
o Answer: a) Greater
29.How many times will the following PHP code print "Hello"?
php
Copy code
$x = 0;
while ($x < 5) {
echo "Hello";
$x++;
}
o a) 0
o b) 5
o c) Infinite
o d) 1
o Answer: b) 5
30.Which of the following PHP statements will execute when the
condition in an if statement is false?
o a) else
o b) endif
o c) else if
o d) default
o Answer: a) else
31.What will be the output of the following code?
php
Copy code
$x = 10;
if ($x == 10) {
echo "Equal";
} else if ($x < 10) {
echo "Less";
} else {
echo "Greater";
}
o a) Equal
o b) Less
o c) Greater
o d) None of the above
o Answer: a) Equal
32.What will the following PHP code output?
php
Copy code
$x = 10;
if ($x < 10) {
echo "Less";
} else if ($x == 10) {
echo "Equal";
} else {
echo "Greater";
}
o a) Less
o b) Equal
o c) Greater
o d) None of the above
o Answer: b) Equal
33.Which of the following is the correct syntax for a switch statement in
PHP?
o a) switch(x) { case 1: echo "Hello"; break; }
o b) switch x { case 1: echo "Hello"; }
o c) if switch(x) { case 1: echo "Hello"; }
o d) switch case(x): echo "Hello";
o Answer: a) switch(x) { case 1: echo "Hello"; break; }
34.What is the purpose of the break statement in a switch statement?
o a) To terminate the current loop
o b) To exit from a switch case
o c) To skip to the next case
o d) To print the case value
o Answer: b) To exit from a switch case
35.Which of the following will cause the code to output Equal?
php
Copy code
$x = 5;
$y = 10;
if ($x > $y) {
echo "Greater";
} else if ($x == $y) {
echo "Equal";
} else {
echo "Lesser";
}
o a) Greater
o b) Equal
o c) Lesser
o d) None of the above
o Answer: b) Equal
36. Which of the following is used to include the PHP file once, even if it has been
included before?
o a) include()
o b) require()
o c) include_once()
o d) require_once()
o Answer: c) include_once()
37. What is the default file extension for PHP files?
o a) .php5
o b) .html
o c) .php
o d) .htm
o Answer: c) .php
38. Which of the following functions is used to check if a variable is set and is not
null?
o a) isset()
o b) empty()
o c) var_dump()
o d) check()
o Answer: a) isset()
39. Which PHP function is used to get the length of a string?
o a) strlen()
o b) str_len()
o c) count()
o d) length()
o Answer: a) strlen()
40. Which of the following PHP functions can be used to redirect a user to another
page?
o a) header()
o b) redirect()
o c) go()
o d) move()
o Answer: a) header()
41. What is the purpose of the $_POST superglobal array in PHP?
o a) It stores data passed via URL parameters
o b) It stores data submitted via HTTP POST method
o c) It stores session data
o d) It stores cookies data
o Answer: b) It stores data submitted via HTTP POST method
42. Which of the following is used to start a session in PHP?
o a) start_session()
o b) session_start()
o c) begin_session()
o d) initialize_session()
o Answer: b) session_start()
43. What will happen if include() fails to find the file?
o a) A fatal error will occur
o b) A warning will be shown, but the script continues
o c) The script will stop execution
o d) It will throw an exception
o Answer: b) A warning will be shown, but the script continues
44. What type of error is triggered by calling an undefined function in PHP?
o a) Parse error
o b) Fatal error
o c) Notice
o d) Warning
o Answer: b) Fatal error
45. Which of the following superglobal arrays in PHP is used to store data from
URL parameters?
o a) $_GET
o b) $_SESSION
o c) $_FILES
o d) $_REQUEST
o Answer: a) $_GET
46. Which of the following PHP functions is used to escape special characters in a
string for use in SQL queries?
o a) escape_string()
o b) htmlspecialchars()
o c) mysql_real_escape_string()
o d) escape_html()
o Answer: c) mysql_real_escape_string()
47. Which of the following is the correct way to handle errors in PHP?
o a) try-catch blocks
o b) Using set_error_handler()
o c) Using ini_set() to change error settings
o d) All of the above
o Answer: d) All of the above
48. What is the default value returned by the empty() function in PHP if the
variable is not set or is empty?
o a) false
o b) null
o c) true
o d) undefined
o Answer: c) true
49. What is the purpose of the unset() function in PHP?
o a) To reset a variable
o b) To delete a variable from memory
o c) To change a variable's value to null
o d) To destroy a session
o Answer: b) To delete a variable from memory
50. Which of the following data types are supported by PHP?
o a) Integer
o b) String
o c) Array
o d) All of the above
o Answer: d) All of the above
51. Which of the following PHP functions is used to read data from a file?
o a) read()
o b) file_get_contents()
o c) get_file()
o d) fopen()
o Answer: b) file_get_contents()
52. Which PHP function is used to send a cookie to the client's browser?
o a) setcookie()
o b) sendcookie()
o c) cookie()
o d) set()
o Answer: a) setcookie()
53. Which of the following statements is true about PHP arrays?
o a) PHP arrays are always indexed
o b) PHP arrays are always associative
o c) PHP arrays can be both indexed and associative
o d) PHP arrays cannot store different data types
o Answer: c) PHP arrays can be both indexed and associative
54. Which of the following will enable error reporting in PHP?
o a) error_reporting(E_ALL);
o b) set_error_reporting(E_ALL);
o c) report_errors(E_ALL);
o d) display_errors(E_ALL);
o Answer: a) error_reporting(E_ALL);
55. Which PHP function is used to remove white spaces or other characters from
both ends of a string?
o a) trim()
o b) strip_tags()
o c) stripslashes()
o d) clean()
o Answer: a) trim()

5 MARKS

1. Explain how to embed PHP code into an HTML file and provide an
example.
2. Describe the different data types available in PHP and give an example
for each.
3. What is the significance of the $ symbol in PHP? Illustrate with an
example.
4. How can you embed HTML code within a PHP file and display output
using PHP?
5. What are the different ways to define a variable in PHP, and what are the
rules for naming a variable?
6. Explain the working of the if, else if, and else statements with an
example.
7. What are the different comparison operators in PHP and how are they
used in conditional statements?

10 MARKS

1.Explain the basic syntax of PHP and the role of the <?php ?> tags in
embedding PHP code within HTML.

2.Describe how PHP variables are declared, initialized, and used, along with
an explanation of variable scope and global vs local variables.

3.Compare and contrast the use of if, else if, and else statements in PHP, with
examples to demonstrate their practical application in conditional logic.

4.Explain the different data types in PHP (integer, float, string, array, and
object), and provide examples of how each is used in PHP scripts.

5.Describe the purpose of PHP operators (arithmetic, comparison, logical,


and assignment operators) and provide examples of how they can be used to
manipulate variables.

UNIT – 3

PHP switch Statement


The switch statement is similar to the series of if-else statements. The
switch statement performs in various cases i.e. it has various cases to
which it matches the condition and appropriately executes a particular
case block. It first evaluates an expression and then compares it with the
values of each case. If a case matches then the same case is executed.
To use the switch, we need to get familiar with two different keywords
namely, break and default.
• break: The break statement is used to stop the automatic control flow
into the next cases and exit from the switch case.
• default: The default statement contains the code that would execute if
none of the cases match.
Flowchart of switch statement:

Syntax:
switch(expression)
{
case val1:
// Code Statement
break;
case val2:
// Code statement
break;
...

default:
// Code Statement
}
Example 1: The following code demonstrates the switch statement.
• PHP
<?php

$x = 2;
switch ($x) {
case 1:
printf("Choice is 1");
break;
case 2:
printf("Choice is 2");
break;
case 3:
printf("Choice is 3");
break;
default:
printf("Choice other than 1, 2 and 3");

?>
Output
Choice is 2
Example 2:
• PHP
<?php

$n='C';
switch($n)
{
case 'A':
case 'B':
printf("A and B\n");
break;

case 'C':
case 'D':
printf("C and D\n");
break;

default:printf("Alphabet is greater than D\n");

?>
Output
C and D
PHP while Loop
The while loop is the simple loop that executes nested statements
repeatedly while the expression value is true. The expression is checked
every time at the beginning of the loop, and if the expression evaluates
to true then the loop is executed otherwise loop is terminated.
Flowchart of While Loop:
Syntax:
while (if the condition is true) {
// Code is executed
}
Example 1: This example uses a while loop to display numbers.
• PHP
<?php

// Declare a number
$num = 10;

// While Loop
while ($num < 20) {
echo $num . "\n";
$num += 2;
}
?>
Output
10
12
14
16
18
while-endWhile loop:
Syntax:
while (if the condition is true):
// Code is executed
...
endwhile;
Example 2: This example uses while and endwhile to display the
numbers.
• PHP
<?php

// Declare a number
$num = 10;

// While Loop
while ($num < 20):
echo $num . "\n";
$num += 2;
endwhile;
?>
Output
10
12
14
16
18

PHP for Loop


The for loop is the most complex loop in PHP that is used when the user knows
how many times the block needs to be executed. The for loop contains the
initialization expression, test condition, and update expression (expression for
increment or decrement).
Flowchart of for Loop:
Syntax:
for (initialization expression; test condition; update expression) {
// Code to be executed
}
Loop Parameters:
• Initialization Expression: In this expression, we have to initialize the
loop counter to some value. For example: $num = 1;
• Test Condition: In this expression, we have to test the condition. If the
condition evaluates to “true” then it will execute the body of the loop and
go to the update expression otherwise it will exit from the for loop. For
example: $num <= 10;
• Update Expression: After executing the loop body, this expression
increments/decrements the loop variable by some value. For example:
$num += 2;
Example 1: The following code shows a simple example using for loop.
• PHP
<?php
// for Loop to display numbers
for( $num = 0; $num < 20; $num += 5) {
echo $num . "\n";
}

?>
Output
0
5
10
15
Example 2: The following code shows another example of for loop.
• PHP
<?php

// for Loop to display numbers


for( $num = 1; $num < 50; $num++)
{
if($num % 5 == 0)
echo $num . "\n";
}
?>
Output
5
10
15
20
25
30
35
40
45
PHP | Functions
Last Updated : 08 Jul, 2024



A function is a block of code written in a program to perform some
specific task. We can relate functions in programs to employees in a
office in real life for a better understanding of how functions work.
Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information
about the statistics from the boss, performs calculations and calculate the
budget and shows the result to his boss. Functions works in a similar
manner. They take informations as parameter, executes a block of
statements or perform operations on this parameters and returns the
result.
PHP provides us with two major types of functions:

• Built-in functions : PHP provides us with huge collection of built-in


library functions. These functions are already coded and stored in form of
functions. To use those we just need to call them as per our requirement
like, var_dump, fopen(), print_r(), gettype() and so on.
• User Defined Functions : Apart from the built-in functions, PHP allows
us to create our own customised functions called the user-defined
functions.
Using this we can create our own packages of code and use it wherever
necessary by simply calling it.

Why should we use functions?

• Reusability: If we have a common code that we would like to use at


various parts of a program, we can simply contain it within a function and
call it whenever required. This reduces the time and effort of repetition of
a single code. This can be done both within a program and also by
importing the PHP file, containing the function, in some other program
• Easier error detection: Since, our code is divided into functions, we can
easily detect in which function, the error could lie and fix them fast and
easily.
• Easily maintained: As we have used functions in our program, so if
anything or any line of code needs to be changed, we can easily change it
inside the function and the change will be reflected everywhere, where
the function is called. Hence, easy to maintain.

Creating a Function

While creating a user defined function we need to keep few things in


mind:
1. Any name ending with an open and closed parenthesis is a function.
2. A function name always begins with the keyword function.
3. To call a function we just need to write its name followed by the
parenthesis
4. A function name cannot start with a number. It can start with an alphabet
or underscore.
5. A function name is not case-sensitive.

Syntax:

function function_name(){
executable code;
}

Example:

PHP
1
<?php
2

3
function funcGeek()
4
{
5
echo "This is Geeks for Geeks";
6
}
7

8
// Calling the function
9
funcGeek();
10

11
?>
Output:
This is Geeks for Geeks

Function Parameters or Arguments

The information or variable, within the function’s parenthesis, are called


parameters. These are used to hold the values executable during runtime.
A user is free to take in as many parameters as he wants, separated with
a comma(,) operator. These parameters are used to accept inputs during
runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a
parameter is used to hold those arguments. In common term, both
parameter and argument mean the same. We need to keep in mind that
for every parameter, we need to pass its corresponding argument.
Syntax:

function function_name($first_parameter, $second_parameter) {


executable code;
}

Example:

PHP
1
<?php
2

3
// function along with three parameters
4
function proGeek($num1, $num2, $num3)
5
{
6
$product = $num1 * $num2 * $num3;
7
echo "The product is $product";
8
}
9

10
// Calling the function

// Passing three arguments


proGeek(2, 3, 5);

?>
Output:

The product is 30

Setting Default Values for Function parameter

PHP allows us to set default argument values for function parameters. If


we do not pass any argument for a parameter with default value then
PHP will use the default set value for this parameter in the function call.
Example:

PHP

<?php

// function with default parameter

function defGeek($str, $num=12)

echo "$str is $num years old \n";

// Calling the function

defGeek("Ram", 15);

// In this call, the default value 12

// will be considered
defGeek("Adam");

?>
Output:

Ram is 15 years old


Adam is 12 years old

In the above example, the parameter $num has a default value 12, if we
do not pass any value for this parameter in a function call then this
default value 12 will be considered. Also the parameter $str has no
default value , so it is compulsory.

Returning Values from Functions

Functions can also return values to the part of program from where it is
called. The return keyword is used to return value back to the part of
program, from where it was called. The returning value may be of any
type including the arrays and objects. The return statement also marks
the end of the function and stops the execution after that and returns the
value.
Example:

PHP

<?php

// function along with three parameters

function proGeek($num1, $num2, $num3)

$product = $num1 * $num2 * $num3;

return $product; //returning the product

// storing the returned value

$retValue = proGeek(2, 3, 5);

echo "The product is $retValue";


?>
Output:

The product is 30

Parameter passing to Functions

PHP allows us two ways in which an argument can be passed into a


function:

• Pass by Value: On passing arguments using pass by value, the value of


the argument gets changed within a function, but the original value
outside the function remains unchanged. That means a duplicate of the
original value is passed as an argument.
• Pass by Reference: On passing arguments as pass by reference, the
original value is passed. Therefore, the original value gets altered. In pass
by reference we actually pass the address of the value, where it is stored
using ampersand sign(&).

Example:

PHP

<?php
// pass by value

function valGeek($num) {

$num += 2;

return $num;

// pass by reference

function refGeek(&$num) {

$num += 10;
return $num;

$n = 10;

valGeek($n);

echo "The original value is still $n \n";

refGeek($n);

echo "The original value changes to $n";

?>
Output:

The original value is still 10


The original value changes to 20

PHP array() Function


The array() function is an inbuilt function in PHP which is used to create an
array. There are three types of array in PHP:
• Indexed array: The array which contains numeric index.
Syntax:
array( val1, val2, val3, ... )
• Associative array: The array which contains name as keys.
Syntax:
array( key=>val, key=>val, key=>value, ... )
• Multidimensional array: The array which contains one or more arrays.
Syntax:
• array( array( val11, val12, ...)
• array( val21, val22, ...)
... )
Parameters: This function accepts atmost two parameters as mentioned
above and described below:
• val: This parameter is used to hold the value of array.
• key: This parameter is used to hold the key value:
Return Value: This function returns an array of parameters.
Below programs illustrates the array() function in PHP:
Program 1: This example illustrate the Indexed array.
<?php

// Create an array
$sub = array("DBMS", "Algorithm", "C++", "JAVA");

// Find length of array


$len = count( $sub );

// Loop to print array elements


for( $i = 0; $i < $len; $i++) {
echo $sub[$i] . "\n";
}
?>
Output:
DBMS
Algorithm
C++
JAVA
Program 2: This example illustrate the Associative array.
<?php

// Declare an associative array


$detail = array( "Name"=>"GeeksforGeeks",
"Address"=>"Noida",
"Type"=>"Educational site");

// Display the output


var_dump ($detail);
?>
Output:
array(3) {
["Name"]=>
string(13) "GeeksforGeeks"
["Address"]=>
string(5) "Noida"
["Type"]=>
string(16) "Educational site"
}
Program 3: This example illustrate the Multidimensional array.
<?php

// Declare 2D array
$detail = array(array(1, 2, 3, 4),
array(5, 6, 7, 8));

// Display the output


var_dump ($detail);
?>
Output:
array(2) {
[0]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
[1]=>
array(4) {
[0]=>
int(5)
[1]=>
int(6)
[2]=>
int(7)
[3]=>
int(8)
}
}
Table of Content
• Using for Loop
• Using foreach Loop
• Using while Loop with each() Function
• Using array_walk() with a callback function
• Using array_map() with a Callback Function
• Using array_reduce()
Using for Loop
The PHP for loop is a basic way to iterate through an array. It is useful
when you need to access array elements by their index.
PHP

<?php

$arr = [1, 2, 3, 4, 5];

$length = count($arr);

for ($i = 0; $i < $length; $i++) {

echo $arr[$i] . ' ';

?>

Output
12345
Using foreach Loop
The PHP foreach loop is an method to iterate through an array. There is
no need of index number in foreach loop.
PHP

<?php

$arr = [1, 2, 3, 4, 5];

foreach ($arr as $val) {

echo $val . ' ';

}
?>

Output
12345
Using while Loop with each() Function
The PHP each() function can be used in combination with a while
loop to iterate through an array while maintaining the internal pointer.
PHP

<?php

$arr = ['apple', 'banana', 'cherry'];

while ($element = each($arr)) {

echo $element['key'] . ' => '

. $element['value'] . "\n";

?>

Output
0 => apple
1 => banana
2 => cherry
Using array_walk() with a callback function
In PHP, `array_walk()` iterates through an array, applying a user-defined
callback function to each element. The callback receives each array
element as an argument, allowing for custom operations on array values
without needing to manage iteration explicitly.
Example:
PHP

<?php

$array = [1, 2, 3, 4, 5];


// Callback function to print each element

function printElement($value) {

echo $value . " ";

// Applying the callback function to each element of the array

array_walk($array, 'printElement');

?>

Output
12345
Using array_map() with a Callback Function
The array_map() function in PHP applies a callback function to each
element of an array, creating and returning a new array with the results
of the callback function.
Example:
PHP

<?php

$array = [1, 2, 3, 4, 5];

// Callback function to increment each element by 1

function increment($value) {

return $value + 1;

// Applying the callback function to each element of the array

$newArray = array_map('increment', $array);

// Print the new array


foreach ($newArray as $val) {

echo $val . ' ';


}

?>

Output
23456
Using array_reduce()
This approach uses array_reduce() to apply a callback function to each
element of the array, reducing the array to a single cumulative value.
Example:
PHP

<?php

$array = array('apple', 'banana', 'cherry');

array_reduce($array, function($carry, $item) {

echo $item . "\n";

});

?>

Output
apple
banana
cherry

• Approach 1: Using Array.filter() method


• Approach 2: Using Object.values()
• Approach 3: Using the reduce() method
• Approach 4: Using for…of loop
• Approach 5: Using forEach()
• Approach 6: Using Map
Approach 1: Using Array.filter() method
In this approach, we will create an array having multiple objects in itself
and then use Array.filter() method we will filter out certain values from
that complete array of objects.
Syntax:
array.filter(callback(element, index, arr), thisValue);
Example: in this example, we are using the above-explained approach.
JavaScript

let fruits = [

fruit_name: "Apple",

fruit_color: "Red",

},

fruit_name: "Pomegranate",

fruit_color: "Red",

},

fruit_name: "Grapes",

fruit_color: "Green",

},

fruit_name: "Kiwi",

fruit_color: "Green",

},

];
let filtered_fruits = fruits.filter((fruit) =>

fruit.fruit_color === "Red");

console.log(filtered_fruits);

Output
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
]
Approach 2: Using Object.values()
In this approach, we will use the same array containing multiple objects
which we have created previously, and here we will create another
function that will be responsible for containing our logic for the above-
enlightened problem statement.
Then the first part of our logic will be using Object.values() method that
will actually accumulate all the object values for us and just after that we
will use Array.reduce() method which will reduce our array into objects
and then using nullish coalescing operator (??) we will either add the
property value inside the accumulator value (part of reduce method) or
we will add an empty array instead of it ([ ]).
The second part of our logic says that we have to push the current value
inside the accumulator value itself that contains the previously added
value in it and then at the end, we will return the accumulator value
itself.
Syntax:
Object.values(obj)
Example: This example shows the implementation of the above-
explained approach.
JavaScript

let fruits = [

{
fruit_name: "Apple",

fruit_color: "Red",

},

{
fruit_name: "Pomegranate",

fruit_color: "Red",

},

fruit_name: "Grapes",

fruit_color: "Green",

},

fruit_name: "Kiwi",

fruit_color: "Green",

},

];

let groupingViaCommonProperty = Object.values(

fruits.reduce((acc, current) => {

acc[current.fruit_color] = acc[current.fruit_color] ?? [];

acc[current.fruit_color].push(current);

return acc;

}, {})

);

console.log(groupingViaCommonProperty);
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Approach 3: Using the reduce() method
The reduce() method in JavaScript applies a function to each element of
an array, accumulating a single result, and returns the final output.
Syntax:
array.reduce( function(total, currentValue, currentIndex, arr),
initialValue );
Example: In this example, we are using the reduce() method and create
an array of arrays containing fruits of the same color. The resultArray
logs the grouped fruits.
JavaScript

const fruits = [

fruit_name: "Apple",

fruit_color: "Red",

},

fruit_name: "Pomegranate",

fruit_color: "Red",

},

fruit_name: "Grapes",
fruit_color: "Green",

},

fruit_name: "Kiwi",

fruit_color: "Green",

},

];

const groupedByColor = fruits.reduce((acc, fruit) => {

const color = fruit.fruit_color;

(acc[color] = acc[color] || []).push(fruit);

return acc;
}, {});

const resultArray = Object.values(groupedByColor);


console.log(resultArray);

Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 4: Using for…of loop
The for…of loop in JavaScript iterates over iterable objects like arrays,
strings, maps, sets, etc. We can use it to group objects in an array based
on a common property.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example, we are using the above-explained approach.
JavaScript
1
const fruits = [

fruit_name: "Apple",

fruit_color: "Red",

},

fruit_name: "Pomegranate",

fruit_color: "Red",

},

fruit_name: "Grapes",

fruit_color: "Green",

},
{

fruit_name: "Kiwi",

fruit_color: "Green",

},

];

const groupedByColor = {};

for (const fruit of fruits) {

const color = fruit.fruit_color;

if (!groupedByColor[color]) {

groupedByColor[color] = [fruit];

} else {

groupedByColor[color].push(fruit);

const resultArray = Object.values(groupedByColor);

console.log(resultArray);

Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...
Output:
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 5: Using forEach()
Using the forEach() method in JavaScript, we can iterate over each
element in an array and group objects based on a common property.
Syntax:
array.forEach(callback(element, index, arr), thisValue)
Example: In this example, the forEach() loop iterates over each fruit in
the fruits array. It checks the fruit_color property, creates an empty array
for color if it doesn’t exist in the groupedByColor object, and then
pushes the fruit into the corresponding array based on its color.
JavaScript

const fruits = [

fruit_name: "Apple",

fruit_color: "Red",

},

fruit_name: "Pomegranate",

fruit_color: "Red",

},
{

fruit_name: "Grapes",

fruit_color: "Green",

},
{

fruit_name: "Kiwi",

fruit_color: "Green",

},

];

const groupedByColor = {};

fruits.forEach((fruit) => {

const color = fruit.fruit_color;

groupedByColor[color] = groupedByColor[color] || [];

groupedByColor[color].push(fruit);

});

const resultArray = Object.values(groupedByColor);

console.log(resultArray);
Output:
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', fruit_color: 'Green' }
]
]
Approach 6: Using Map
Using the Map object, we can efficiently group objects based on a
common property. Map provides better performance for frequent
additions and lookups compared to plain objects.
Syntax:
new Map(iterable);
Example:
JavaScript

const fruits = [

{ fruit_name: "Apple", fruit_color: "Red" },

{ fruit_name: "Pomegranate", fruit_color: "Red" },

{ fruit_name: "Grapes", fruit_color: "Green" },

{ fruit_name: "Kiwi", fruit_color: "Green" },

];

const groupedByColor = new Map();

fruits.forEach((fruit) => {

const color = fruit.fruit_color;

if (!groupedByColor.has(color)) {

groupedByColor.set(color, [fruit]);

} else {

groupedByColor.get(color).push(fruit);

});
const resultArray = Array.from(groupedByColor.values());

console.log(resultArray);

Output
[
[
{ fruit_name: 'Apple', fruit_color: 'Red' },
{ fruit_name: 'Pomegranate', fruit_color: 'Red' }
],
[
{ fruit_name: 'Grapes', fruit_color: 'Green' },
{ fruit_name: 'Kiwi', frui...

MCQ

1. What will be the output of the following code?


php
Copy code
$x = 2;
switch ($x) {
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Default";
}
A) One
B) Two
C) Three
D) Default
Answer: B) Two
2. What happens if there is no break in a switch case? A) The program
will exit the switch
B) It will continue to the next case
C) It will result in an error
D) It will print nothing
Answer: B) It will continue to the next case
3. Which of the following is not a valid type of value for a switch
expression? A) Integer
B) Float
C) Array
D) String
Answer: C) Array
4. Which of the following statements is true regarding the switch
statement? A) It can only have if-else branches
B) It is case-sensitive by default
C) It evaluates each condition without checking the first match
D) It cannot have a default case
Answer: B) It is case-sensitive by default

5. What will be the output of the following PHP code?


php
Copy code
$i = 1;
while ($i <= 3) {
echo $i;
$i++;
}
A) 123
B) 1
C) 12345
D) Infinite Loop
Answer: A) 123
6. Which condition will break an infinite while loop? A) if ($i > 10)
B) break
C) continue
D) None of the above
Answer: B) break
7. How can you prevent an infinite loop when using while in PHP? A)
Use continue
B) Use break when a certain condition is met
C) Add a return statement
D) None of the above
Answer: B) Use break when a certain condition is met
8. What will the following PHP code output?
php
Copy code
$x = 10;
while ($x > 0) {
echo $x . " ";
$x--;
}
A) 10 9 8 7 6 5 4 3 2 1
B) 10 9 8 7 6 5 4 3 2
C) 1 2 3 4 5 6 7 8 9 10
D) Infinite Loop
Answer: A) 10 9 8 7 6 5 4 3 2 1

9. What is the correct syntax for a for loop in PHP? A) for($i = 0; $i < 5;
$i++)
B) for(i = 0; i < 5; i++)
C) for($i; $i <= 5; $i++)
D) for($i = 0; $i < 5)
Answer: A) for($i = 0; $i < 5; $i++)
10.Which loop is best suited when the number of iterations is known
beforehand? A) while
B) for
C) do-while
D) foreach
Answer: B) for
11.What will this PHP code output?
php
Copy code
for ($i = 1; $i <= 3; $i++) {
echo $i;
}
A) 1
B) 12
C) 123
D) 1234
Answer: C) 123
12.In a for loop, if the condition is never true, what happens? A) The
loop will execute infinitely
B) The loop will never execute
C) The loop will execute once
D) An error occurs
Answer: B) The loop will never execute
13.Which of the following is used to declare a function in PHP? A)
function myFunc() { }
B) func myFunc() { }
C) def myFunc() { }
D) declare function myFunc() { }
Answer: A) function myFunc() { }
14.What will be the output of the following PHP code?
php
Copy code
function add($a, $b) {
return $a + $b;
}
echo add(2, 3);
A) 5
B) 23
C) 6
D) Error
Answer: A) 5
15.What does the return keyword do in PHP functions? A) Terminates
the function without returning any value
B) Returns a value and exits the function
C) Prints the value to the screen
D) Stops the program execution
Answer: B) Returns a value and exits the function
16.Which PHP function is used to include the content of one PHP file in
another? A) include()
B) require()
C) require_once()
D) All of the above
Answer: D) All of the above
17.Which PHP function is used to get the length of a string? A) len()
B) strlen()
C) length()
D) str_length()
Answer: B) strlen()
18.How do you create an indexed array in PHP? A) $arr = array(1, 2, 3);
B) $arr = [1, 2, 3];
C) $arr = (1, 2, 3);
D) Both A and B
Answer: D) Both A and B
19.How can you access the first element of an array $arr = [10, 20, 30];?
A) $arr[0]
B) $arr[1]
C) $arr[10]
D) $arr['first']
Answer: A) $arr[0]
20.Which of the following will modify the value of the third element of
an array $arr = [1, 2, 3, 4, 5];? A) $arr[3] = 10;
B) $arr[2] = 10;
C) $arr[1] = 10;
D) $arr[5] = 10;
Answer: B) $arr[2] = 10;
21.What will the count() function do with an array? A) Counts the
elements in an array
B) Displays the array values
C) Deletes an element
D) Changes the array structure
Answer: A) Counts the elements in an array
22.How do you check if an array element exists in PHP? A) isset()
B) array_key_exists()
C) in_array()
D) All of the above
Answer: D) All of the above
23.Which function in PHP is used to add an element to the end of an
array? A) array_push()
B) array_pop()
C) array_add()
D) array_insert()
Answer: A) array_push()
24.Which PHP function removes the last element of an array? A)
array_pop()
B) array_shift()
C) array_unshift()
D) array_slice()
Answer: A) array_pop()
25.How do you create an associative array in PHP? A) $arr = ["a" => 1,
"b" => 2];
B) $arr = [1, 2, 3];
C) $arr = (a = 1, b = 2);
D) $arr = array("a", "b", 1, 2);
Answer: A) $arr = ["a" => 1, "b" => 2];
26.Which loop is used to iterate over an array in PHP? A) foreach
B) for
C) while
D) All of the above
Answer: A) foreach
27.How do you loop through an associative array in PHP? A)
foreach($array as $key => $value)
B) for($key = 0; $key < count($array); $key++)
C) while($value = each($array))
D) for($i = 0; $i < sizeof($array); $i++)
Answer: A) foreach($array as $key => $value)
28.What will the following code print?
php
Copy code
$arr = [1, 2, 3];
foreach ($arr as $value) {
echo $value;
}
A) 1 2 3
B) 123
C) 1
D) 3
Answer: B) 123
29.What is the purpose of array_map() in PHP? A) Sorts an array
B) Applies a callback function to each element of an array
C) Returns a subset of an array
D) Combines multiple arrays
Answer: B) Applies a callback function to each element of an array
30.Which of the following functions returns all the keys of an array? A)
array_keys()
B) array_values()
C) array_flip()
D) array_unique()
Answer: A) array_keys()
31.How do you store form selection values in an array in PHP? A)
$_POST['field_name']
B) $_GET['field_name']
C) Both A and B
D) None of the above
Answer: C) Both A and B
32.What does the $_POST superglobal contain? A) Values submitted via
GET
B) Values submitted via POST method
C) Cookie values
D) Server information
Answer: B) Values submitted via POST method
33.Which PHP function would you use to group form selections into an
array? A) explode()
B) implode()
C) array_merge()
D) array_map()
Answer: A) explode()
34.How can you retrieve the value of a checkbox that was selected in a
form? A) $_POST['checkbox_name']
B) $_POST['checkbox_name[]']
C) $_GET['checkbox_name']
D) $_POST['checkbox_name[0]']
Answer: B) $_POST['checkbox_name[]']
35.Which function sorts an array in ascending order in PHP? A)
array_sort()
B) sort()
C) array_order()
D) arrange()
Answer: B) sort()
36.What does the array_reverse() function do? A) Sorts an array in
reverse order
B) Returns the keys of an array in reverse
C) Reverses the order of an array without changing its keys
D) Reverses the array values
Answer: C) Reverses the order of an array without changing its keys
37.Which of the following is used to join array elements into a string? A)
implode()
B) explode()
C) join()
D) Both A and C
Answer: D) Both A and C
38.Which function removes duplicate elements from an array? A)
array_unique()
B) array_diff()
C) array_merge()
D) array_filter()
Answer: A) array_unique()
39.How can you combine two arrays into one in PHP? A) merge()
B) combine()
C) array_merge()
D) array_combine()
Answer: C) array_merge()
40.What function would you use to find the intersection of two arrays?
A) array_merge()
B) array_diff()
C) array_intersect()
D) array_union()
Answer: C) array_intersect()
41.What does the array_shift() function do in PHP? A) Removes the last
element of an array
B) Removes the first element of an array
C) Adds an element to the beginning of the array
D) Sorts the array in ascending order
Answer: B) Removes the first element of an array
42.Which of the following functions adds an element to the beginning of
an array? A) array_unshift()
B) array_push()
C) array_add()
D) array_insert()
Answer: A) array_unshift()
43.Which function is used to check if an array contains a specific value?
A) array_key_exists()
B) in_array()
C) array_exists()
D) isset()
Answer: B) in_array()
44.What does the array_slice() function do in PHP? A) Returns a portion
of the array
B) Merges two arrays
C) Reverses the order of an array
D) Filters the elements of an array
Answer: A) Returns a portion of the array
45.Which function is used to change all the keys of an array to their
values? A) array_flip()
B) array_map()
C) array_key_exists()
D) array_change_key_case()
Answer: A) array_flip()
46.How do you check if a key exists in an associative array? A) isset()
B) array_key_exists()
C) key_exists()
D) in_array()
Answer: B) array_key_exists()
47.Which of the following functions adds elements at the end of an
associative array? A) array_push()
B) array_unshift()
C) array_append()
D) array_add()
Answer: A) array_push()
48.Which function merges two associative arrays? A) array_merge()
B) array_push()
C) array_add()
D) array_combine()
Answer: A) array_merge()
49.How do you count the number of elements in an associative array?
A) count()
B) sizeof()
C) array_count()
D) Both A and B
Answer: D) Both A and B
50.Which of the following functions retrieves the first element of an
associative array? A) array_shift()
B) array_pop()
C) reset()
D) end()
Answer: C) reset()

5 MARKS
1. Explain the difference between switch and if-else statements in PHP.
2. What is the purpose of a while() loop in PHP and how does it differ from
a do-while() loop?
3. How does a for() loop work in PHP? Provide an example.
4. Describe how to define a function in PHP and call it.
5. How do you create an indexed array in PHP? Give an example.
6. What is the significance of the array_push() function in PHP?
7. How can you modify an element in an array in PHP? Explain with an
example.
8. What is the foreach() loop used for in PHP and how does it work with
arrays?
9. How do you group multiple form selections into an array in PHP?
10.How do you check if an array contains a specific value in PHP?
11.Explain how the array_merge() function works in PHP with an example.
12.What is the role of isset() and empty() functions in PHP with arrays?
13.Describe how you can use array_map() to process elements in an array.
14.How do you add elements to the beginning of an array in PHP? Explain
with an example.
15.What is the array_slice() function in PHP and how is it used?
10 MARKS
1. Explain the process of creating, modifying, and accessing elements in
indexed and associative arrays in PHP.
2. Compare and contrast switch() and if-else statements with examples in
PHP.
3. How does the while() loop work in PHP? Illustrate with an example and
discuss potential issues like infinite loops.
4. Describe the for() loop structure in PHP and provide a real-world
scenario where it is useful.
5. What is the importance of functions in PHP? Create a function that
accepts parameters and returns a result.
6. Discuss the concept of array functions in PHP with examples of
array_map(), array_filter(), and array_reduce().
7. Explain the concept of processing arrays using loops, especially with
foreach(), and demonstrate with examples.
8. How would you handle form selections in PHP and group the values
using arrays? Provide an example.
9. Describe how to modify arrays in PHP using functions like
array_splice(), array_slice(), and array_merge().
10.Explain the difference between array_keys() and array_values() in PHP
and illustrate their usage with examples.
UNIT – IV

1. fopen() and fread() Functions


• fopen() is used to open a file, and fread() is used to read the contents of
the file.
• This is one of the most common methods for reading a file.
Example:
php
Copy code
<?php
// Open the file in read mode
$file = fopen("example.txt", "r");

// Check if the file is opened successfully


if ($file) {
// Read the file content
$contents = fread($file, filesize("example.txt"));
echo $contents;

// Close the file after reading


fclose($file);
} else {
echo "Error opening the file.";
}
?>
Explanation:
• fopen() opens the file "example.txt" in read mode ("r").
• fread() reads the file content. The second argument
(filesize("example.txt")) specifies the number of bytes to read. Here, we
read the entire file.
• fclose() closes the file after reading.
2. file_get_contents() Function
• file_get_contents() is a simpler way to read an entire file into a string. It
is useful when you want to read the entire file content in one go.
Example:
php
Copy code
<?php
// Read the entire file into a string
$fileContents = file_get_contents("example.txt");

// Check if the file reading was successful


if ($fileContents !== false) {
echo $fileContents;
} else {
echo "Error reading the file.";
}
?>
Explanation:
• This function reads the entire file contents and returns it as a string.
• It’s a very simple and effective way to read small to medium-sized files.
3. fgets() Function
• fgets() reads a file line by line. It’s commonly used for reading large files
without loading the entire file into memory at once.
Example:
php
Copy code
<?php
// Open the file in read mode
$file = fopen("example.txt", "r");

// Check if the file is opened successfully


if ($file) {
// Read the file line by line
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}

// Close the file after reading


fclose($file);
} else {
echo "Error opening the file.";
}
?>
Explanation:
• fgets() reads the file line by line.
• The while loop continues until it reaches the end of the file.
• Each line is outputted one at a time.
4. file() Function
• The file() function reads a file and returns its contents as an array, with
each line as an element in the array.
Example:
php
Copy code
<?php
// Read the entire file into an array
$lines = file("example.txt");

// Check if the file was read successfully


if ($lines !== false) {
foreach ($lines as $line) {
echo $line . "<br>";
}
} else {
echo "Error reading the file.";
}
?>
Explanation:
• file() reads the file and returns each line as an element in an array.
• The foreach loop is used to output each line.
5. fgetc() Function
• fgetc() reads a single character from a file at a time.
Example:
php
Copy code
<?php
// Open the file in read mode
$file = fopen("example.txt", "r");

if ($file) {
// Read one character at a time
while (($char = fgetc($file)) !== false) {
echo $char;
}

// Close the file after reading


fclose($file);
} else {
echo "Error opening the file.";
}
?>
Explanation:
• fgetc() is used to read one character at a time.
• This method is useful if you need to process the file character by
character.
6. readfile() Function
• The readfile() function reads a file and directly outputs its content to the
browser. It is simple to use when you just want to display or send a file's
contents.
Example:
php
Copy code
<?php
// Output the file content directly to the browser
if (readfile("example.txt") === false) {
echo "Error reading the file.";
}
?>
Explanation:
• readfile() directly outputs the contents of the file, making it useful for
simple cases where you don't need to manipulate the file content.
Key Considerations:
• File Pointer: Functions like fread(), fgets(), and fgetc() maintain a file
pointer. Once the pointer reaches the end of the file, further reads will
return false.
• Error Handling: Always check if the file was successfully opened
before attempting to read it. This can be done by checking if fopen()
returns a valid resource or if file_get_contents()/file() returns false.
• Memory Considerations: For large files, it’s better to read them line-by-
line (e.g., using fgets()) or in chunks to avoid consuming too much
memory.
These are the fundamental methods for reading files in PHP. The choice
of method depends on how you want to process the file (e.g., reading the
entire file, line-by-line, or character-by-character).

In PHP, reading from and writing to files is a common task in web


development, especially for tasks such as reading configuration files,
processing data files, or logging information. PHP provides built-in
functions for handling file operations, making it straightforward to
perform file read and write operations.
Reading from a File:
• Use fopen() to open a file pointer.
• Use fgets() or fread( ) to read data from the file.
• Close the file pointer using fclose( ) when done.
Writing to a File:
• Use fopen() with mode 'w' or 'a' to open a file pointer for writing.
• Use fwrite() to write data to the file.
• Close the file pointer using fclose() when done.
Example (Reading from a File):
// Open a file for reading
$handle = fopen("file.txt", "r");

// Read data from the file


while (($line = fgets($handle)) !== false) {
echo $line;
}

// Close the file handle


fclose($handle);
Example (Writing to a File):
// Open a file for writing (create if not exists, truncate if exists)
$handle = fopen("file.txt", "w");

// Write data to the file


fwrite($handle, "Hello, World!\n");

// Close the file handle


fclose($handle);
MCQ
1. Which function is used to open a file in PHP?
o a) open()
o b) fopen()
o c) file()
o d) openfile()
o Answer: b) fopen()
2. What does the fopen() function return when the file cannot be
opened?
o a) False
o b) Null
o c) 0
o d) Error message
o Answer: a) False
3. Which function is used to read a line from a file in PHP?
o a) readline()
o b) fread()
o c) fgets()
o d) fgetc()
o Answer: c) fgets()
4. Which function is used to read an entire file into a string?
o a) file()
o b) file_get_contents()
o c) read_file()
o d) fget_contents()
o Answer: b) file_get_contents()
5. Which function is used to check if the end of a file has been reached?
o a) file_end()
o b) feof()
o c) fend()
o d) eof()
o Answer: b) feof()
6. What does fclose() do in PHP file handling?
o a) Opens the file
o b) Reads the file
o c) Closes the file
o d) Writes data to the file
o Answer: c) Closes the file
7. Which of the following functions returns an array of lines from a
file?
o a) file_get_contents()
o b) fgets()
o c) file()
o d) fread()
o Answer: c) file()
8. What is the maximum number of characters that fgets() reads from a
file?
o a) It reads the entire file
o b) 1024 characters
o c) 4096 characters
o d) It reads a single line until EOF
o Answer: d) It reads a single line until EOF
9. What does file_exists() check in PHP?
o a) If the file is readable
o b) If the file exists on the server
o c) If the file is writable
o d) If the file is empty
o Answer: b) If the file exists on the server
10.Which function in PHP can be used to write to a file?
o a) write()
o b) fwrite()
o c) file_put_contents()
o d) Both b and c
o Answer: d) Both b and c
11.Which of the following functions is used to read a file in binary
mode?
o a) fread()
o b) fgets()
o c) file()
o d) file_get_contents()
o Answer: a) fread()
12.What does fread() function return?
o a) A string of the read data
o b) An array of lines
o c) The file pointer
o d) The file contents as an object
o Answer: a) A string of the read data
13.What will happen if fopen() is called with the 'r' mode and the file
does not exist?
o a) It creates the file
o b) It returns false
o c) It raises an error
o d) It returns null
o Answer: b) It returns false
14.Which of the following functions is used to read a file one byte at a
time?
o a) fgetc()
o b) fread()
o c) file_get_contents()
o d) fgets()
o Answer: a) fgetc()
15.How can you check if a file is readable in PHP before opening it?
o a) is_readable()
o b) check_read()
o c) file_readable()
o d) read_check()
o Answer: a) is_readable()
16.Which PHP function reads the entire content of a file into an array,
one element per line?
o a) file()
o b) file_get_contents()
o c) readfile()
o d) fgets()
o Answer: a) file()
17.How would you append data to a file in PHP?
o a) Use fopen() with mode 'a'
o b) Use file_put_contents() with FILE_APPEND
o c) Both a and b
o d) Use fwrite() with append option
o Answer: c) Both a and b
18.Which function would you use to read a file in chunks?
o a) fgets()
o b) file_get_contents()
o c) fread()
o d) file()
o Answer: c) fread()
19.What will feof() return if the end of the file has not been reached?
o a) 1
o b) 0
o c) Null
o d) False
o Answer: b) 0
20.Which PHP function returns the last error when a file operation
fails?
o a) error_get_last()
o b) ferror()
o c) file_error()
o d) get_file_error()
o Answer: b) ferror()
21.Which PHP function can be used to check the size of a file?
o a) file_size()
o b) filesize()
o c) fsize()
o d) get_filesize()
o Answer: b) filesize()
22.How can you read a CSV file line by line in PHP?
o a) Using fgetcsv()
o b) Using fget()
o c) Using file()
o d) Using file_get_contents()
o Answer: a) Using fgetcsv()
23.Which function is used to get the contents of a file without opening it
in PHP?
o a) file_get_contents()
o b) readfile()
o c) fget()
o d) fopen()
o Answer: a) file_get_contents()
24.Which PHP function is used to read a file in a non-blocking manner?
o a) file_get_contents()
o b) readfile()
o c) fgets()
o d) stream_get_contents()
o Answer: d) stream_get_contents()
25.Which PHP function can be used to lock a file during read
operations?
o a) flock()
o b) file_lock()
o c) lock_file()
o d) lock()
o Answer: a) flock()
26.Which function is used to read a file character by character?
o a) fgetc()
o b) fgets()
o c) fread()
o d) fwrite()
o Answer: a) fgetc()
27.What will happen if file_get_contents() fails to read the file?
o a) It will return null
o b) It will return false
o c) It will return an empty string
o d) It will return an error message
o Answer: b) It will return false
28.What happens if fwrite() is used on a file that is opened in 'r' mode?
o a) It overwrites the file
o b) It raises an error
o c) It appends to the file
o d) It does nothing
o Answer: b) It raises an error
29.How do you ensure a file is only opened for reading and not writing?
o a) Open with 'r' mode
o b) Open with 'r+' mode
o c) Open with 'w' mode
o d) Open with 'rw' mode
o Answer: a) Open with 'r' mode
30.Which function can be used to get the last modified time of a file in
PHP?
o a) file_last_modified()
o b) get_file_time()
o c) filemtime()
o d) last_modified()
o Answer: c) filemtime()
31.Which of the following modes opens a file for writing and creates the
file if it doesn't exist?
o a) 'r'
o b) 'w'
o c) 'a'
o d) 'x'
o Answer: b) 'w'
32.Which PHP function reads a file until a certain number of bytes are
read?
o a) fread()
o b) file_get_contents()
o c) fgets()
o d) fget()
o Answer: a) fread()
33.Which function in PHP can be used to write data into a file, creating
the file if it doesn’t exist?
o a) fwrite()
o b) file_put_contents()
o c) writefile()
o d) createfile()
o Answer: b) file_put_contents()
34.Which function is used to check whether a file is writable in PHP?
o a) is_writable()
o b) file_writable()
o c) can_write()
o d) check_write()
o Answer: a) is_writable()
35.How can you read a large file efficiently in PHP?
o a) Read the file in chunks
o b) Use file_get_contents()
o c) Use fopen() to read the whole file at once
o d) Use fgetcsv() to read the file
o Answer: a) Read the file in chunks
36.How can you skip over lines while reading a file in PHP?
o a) Use fgets() and ignore lines
o b) Use fseek()
o c) Use fgetcsv() to skip lines
o d) Use file() and filter lines
o Answer: b) Use fseek()
37.Which function is used to read a file until EOF in PHP?
o a) fget()
o b) fgets()
o c) fread()
o d) fgetc()
o Answer: b) fgets()
38.How do you open a file for reading and writing without truncating it
in PHP?
o a) 'r+'
o b) 'w+'
o c) 'a+'
o d) 'rw'
o Answer: a) 'r+'
39.What happens when fwrite() is used to write to a file opened in 'r'
mode?
o a) It writes the data successfully
o b) It raises a warning
o c) It appends the data
o d) It creates a new file
o Answer: b) It raises a warning
40.Which PHP function reads a file in one go and returns the contents
as an array?
o a) file()
o b) file_get_contents()
o c) fget()
o d) readfile()
o Answer: a) file()
41.What happens if you attempt to read from a file that is not open?
o a) PHP automatically opens the file
o b) PHP throws an error
o c) It returns null
o d) It returns false
o Answer: b) PHP throws an error
42.Which of the following modes opens a file for both reading and
writing, and creates the file if it doesn’t exist?
o a) 'r+'
o b) 'w+'
o c) 'a+'
o d) 'r'
o Answer: b) 'w+'
43.What happens if you call fgets() after reaching the end of a file?
o a) It returns false
o b) It returns null
o c) It raises an error
o d) It returns an empty string
o Answer: a) It returns false
44.Which PHP function is used to display the contents of a file directly
to the browser?
o a) readfile()
o b) file_get_contents()
o c) fget()
o d) fread()
o Answer: a) readfile()
45.Which of the following functions will you use to write data into a file
without opening it manually?
o a) file_put_contents()
o b) write_file()
o c) fwrite()
o d) put_file()
o Answer: a) file_put_contents()
46.Which PHP function is used to get the position of the file pointer?
o a) ftell()
o b) fpos()
o c) fseek()
o d) tell()
o Answer: a) ftell()
47.What function is used to move the file pointer to a specific position?
o a) fseek()
o b) fmove()
o c) flock()
o d) ftell()
o Answer: a) fseek()
48.What happens if you try to read from a file opened with the 'w'
mode?
o a) It raises an error
o b) It writes data successfully
o c) It opens the file for reading
o d) It creates a new file
o Answer: a) It raises an error
49.Which function is used to safely read a CSV file in PHP?
o a) fgetcsv()
o b) file_get_contents()
o c) read_csv()
o d) csv_read()
o Answer: a) fgetcsv()
50.What will file_get_contents() do if the file doesn't exist?
o a) Return false
o b) Raise an error
o c) Return null
o d) Return an empty string
o Answer: a) Return false

5 Marks
1. Explain the function of fopen() in file handling in PHP.
2. How does fgets() work in reading data from a file in PHP?
3. Describe the difference between fopen() and file_get_contents() in PHP.
4. What is the purpose of feof() in file reading operations in PHP?
5. How can you read an entire file in PHP using file_get_contents()?
6. What is the significance of fclose() in PHP file handling?
7. Describe how to read a file line by line in PHP.
8. What does file_exists() do in PHP and how is it used in file operations?
9. Explain how to handle errors when reading a file in PHP.
10.How can you read a file into an array in PHP using file()?
11.What is the use of fread() in reading files and how does it differ from
fgets()?
12.How do you check if a file is readable before attempting to read it in
PHP?
13.Discuss the use of file_get_contents() for reading remote files in PHP.
14.What are the benefits of using fgetcsv() for reading CSV files in PHP?
15.How does file() function read a file and return it as an array in PHP?
10 Marks
1. Explain the entire process of reading data from a file in PHP using
fopen(), fgets(), and fclose().
2. How do you handle large files efficiently in PHP while reading them line
by line?
3. Discuss the different ways of reading files in PHP and compare their
performance.
4. Explain the role of file pointers in file reading operations in PHP.
5. Demonstrate the usage of fread() with an example and explain how it
differs from fgets().
6. How does PHP handle file locking during read operations, and what
functions are involved?
7. Discuss the security concerns involved in reading files in PHP and how to
mitigate them.
8. What is the purpose of file_get_contents() and how does it handle file
reading and errors?
9. Explain how to read binary data from a file using PHP and give an
example.
10.How can you implement error handling in PHP when attempting to read a
file that does not exist?
UNIT-V

A PHP session is used to store data on a server rather than the computer
of the user. Session identifiers or SID is a unique number which is used
to identify every user in a session based environment. The SID is used to
link the user with his information on the server like posts, emails etc.
How are sessions better than cookies?
Although cookies are also used for storing user related data, they have
serious security issues because cookies are stored on the user’s computer
and thus they are open to attackers to easily modify the content of the
cookie. Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies
send the user data each time the user views a page. Every time the
browser requests a URL to the server, all the cookie data for that website
is automatically sent to the server within the request.
Below are different steps involved in PHP sessions:
• Starting a PHP Session: The first step is to start up a session. After a
session is started, session variables can be created to store information.
The PHP session_start() function is used to begin a new session.It also
creates a new session ID for the user.
Below is the PHP code to start a new session:

<?php

session_start();

?>

• Storing Session Data: Session data in key-value pairs using


the $_SESSION[] superglobal array.The stored data can be accessed
during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber
and Name:
<?php

session_start();

$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";

?>

• Accessing Session Data: Data stored in sessions can be easily accessed


by firstly calling session_start() and then by passing the corresponding
key to the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber
and Name is shown below:
<?php

session_start();

echo 'The Name of the student is :' . $_SESSION["Name"] . '<br>';


echo 'The Roll number of the student is :' .
$_SESSION["Rollnumber"] . '<br>';

?>
Output:
The Name of the student is :Ajay
The Roll number of the student is :11
• Destroying Certain Session Data: To delete only a certain session
data,the unset feature can be used with the corresponding session variable
in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the
associative session array:

<?php
session_start();

if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>
• Destroying Complete Session: The session_destroy() function is used to
completely destroy a session. The session_destroy() function does not
require any argument.
<?php

session_start();
session_destroy();

?>

Important Points
1. The session IDs are randomly generated by the PHP engine .
2. The session data is stored on the server therefore it doesn’t have to be
sent with every browser request.
3. The session_start() function needs to be called at the beginning of the
page, before any output is generated by the script in the browser.

PHP Cookies

A cookie in PHP is a small file with a maximum size of 4KB that the
web server stores on the client computer. They are typically used to keep
track of information such as a username that the site can retrieve to
personalize the page when the user visits the website next time. A cookie
can only be read from the domain that it has been issued from. Cookies
are usually set in an HTTP header but JavaScript can also set a cookie
directly on a browser.
Setting Cookie In PHP: To set a cookie in PHP,
the setcookie() function is used. The setcookie() function needs to be
called prior to any output generated by the script otherwise the cookie
will not be set.
Syntax:
setcookie(name, value, expire, path, domain, security);
Parameters: The setcookie() function requires six arguments in general
which are:
• Name: It is used to set the name of the cookie.
• Value: It is used to set the value of the cookie.
• Expire: It is used to set the expiry timestamp of the cookie after which
the cookie can’t be accessed.
• Path: It is used to specify the path on the server for which the cookie will
be available.
• Domain: It is used to specify the domain for which the cookie is
available.
• Security: It is used to indicate that the cookie should be sent only if a
secure HTTPS connection exists.
Below are some operations that can be performed on Cookies in PHP:
• Creating Cookies: Creating a cookie named Auction_Item and assigning
the value Luxury Car to it. The cookie will expire after 2 days(2 days *
24 hours * 60 mins * 60 seconds).
Example: This example describes the creation of the cookie in PHP.
• PHP

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "cookie is created."
?>
<p>
<strong>Note:</strong>
You might have to reload the
page to see the value of the cookie.
</p>

</body>
</html>

Note: Only the name argument in the setcookie() function is mandatory.


To skip an argument, the argument can be replaced by an empty
string(“”).
Output:

Cookie creation in PHP


Checking Whether a Cookie Is Set Or Not: It is always advisable to
check whether a cookie is set or not before accessing its value. Therefore
to check whether a cookie is set or not, the PHP isset() function is used.
To check whether a cookie “Auction_Item” is set or not, the isset()
function is executed as follows:
Example: This example describes checking whether the cookie is set or
not.
• PHP
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
if (isset($_COOKIE["Auction_Item"]))
{
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
}
else
{
echo "No items for auction.";
}
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>

</body>
</html>
Output:

Checking for the cookie to be set


Accessing Cookie Values: For accessing a cookie value, the PHP
$_COOKIE superglobal variable is used. It is an associative array that
contains a record of all the cookies values sent by the browser in the
current request. The records are stored as a list where the cookie name is
used as the key. To access a cookie named “Auction_Item”, the
following code can be executed.
Example: This example describes accessing & modifying the cookie
value.
• PHP

<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>

</body>
</html>

Output:

Accessing the Cookie value


Deleting Cookies: The setcookie() function can be used to delete a
cookie. For deleting a cookie, the setcookie() function is called by
passing the cookie name and other arguments or empty strings but
however this time, the expiration date is required to be set in the past. To
delete a cookie named “Auction_Item”, the following code can be
executed.
Example: This example describes the deletion of the cookie value.
• PHP
<!DOCTYPE html>
<?php
setcookie("Auction_Item", "Luxury Car", time() + 2 * 24 * 60 * 60);
?>
<html>
<body>
<?php
setcookie("Auction_Item", "", time() - 60);
?>
<?php
echo "cookie is deleted"
?>
<p>
<strong>Note:</strong>
You might have to reload the page
to see the value of the cookie.
</p>

</body>
</html>
Output:

Deleting the Cookie


Important Points:
• If the expiration time of the cookie is set to 0 or omitted, the cookie will
expire at the end of the session i.e. when the browser closes.
• The same path, domain, and other arguments should be passed that were
used to create the cookie in order to ensure that the correct cookie is
deleted.

MCQ
1.What is the purpose of a session in web development?
• A. To store user data permanently
• B. To maintain state across multiple pages
• C. To authenticate users
• D. To store data on the server permanently
Answer: B. To maintain state across multiple pages
2. Which PHP function is used to start a session?
• A. session_start()
• B. start_session()
• C. initialize_session()
• D. begin_session()
Answer: A. session_start()
3. How do you set a session variable in PHP?
• A. $_SESSION["variable"] = "value";
• B. session_set("variable", "value");
• C. set_session("variable", "value");
• D. session["variable"] = "value";
Answer: A. $_SESSION["variable"] = "value";
4. Which of the following functions is used to destroy all session variables in
PHP?
• A. session_unset()
• B. session_destroy()
• C. unset_session()
• D. destroy_session()
Answer: B. session_destroy()
5. What does the session_unset() function do in PHP?
• A. Ends the session
• B. Deletes all session variables
• C. Clears the session data from the server
• D. Removes the session file
Answer: B. Deletes all session variables
6. What is the default duration of a session in PHP?
• A. 30 minutes
• B. Until the browser is closed
• C. 1 hour
• D. 24 hours
Answer: B. Until the browser is closed
7. What is the PHP superglobal used to access session variables?
• A. $_SESSION
• B. $_COOKIE
• C. $_SERVER
• D. $_POST
Answer: A. $_SESSION
8. How can you check if a session variable is set in PHP?
• A. isset($_SESSION["variable"]);
• B. check_session("variable");
• C. is_session_set("variable");
• D. session_set("variable");
Answer: A. isset($_SESSION["variable"]);
9. Which PHP function is used to set a cookie?
• A. setcookie()
• B. cookie_set()
• C. set_cookie()
• D. create_cookie()
Answer: A. setcookie()
10. Which of the following can be stored in a cookie?
• A. Only strings
• B. Strings, integers, and arrays
• C. Only integers
• D. Only session data
Answer: A. Only strings
11. How do you retrieve a cookie value in PHP?
• A. $_COOKIE["cookie_name"]
• B. getcookie("cookie_name")
• C. cookie("cookie_name")
• D. $_SESSION["cookie_name"]
Answer: A. $_COOKIE["cookie_name"]
12. What is the maximum size of a cookie in PHP?
• A. 1024 bytes
• B. 4096 bytes
• C. 2048 bytes
• D. 512 bytes
Answer: B. 4096 bytes
13. How long does a session last in PHP by default?
• A. Until the browser is closed
• B. 1 hour
• C. 30 minutes
• D. 24 hours
Answer: A. Until the browser is closed
14. Which function removes a session variable in PHP?
• A. unset()
• B. remove_session_variable()
• C. session_remove()
• D. delete_session_variable()
Answer: A. unset()
15. How can you destroy a specific session variable in PHP?
• A. unset($_SESSION["variable"]);
• B. session_unset("variable");
• C. destroy_session_variable("variable");
• D. remove_session("variable");
Answer: A. unset($_SESSION["variable"]);
16. What is the syntax to delete a cookie in PHP?
• A. setcookie("cookie_name", "", time() - 3600);
• B. delete_cookie("cookie_name");
• C. unsetcookie("cookie_name");
• D. remove_cookie("cookie_name");
Answer: A. setcookie("cookie_name", "", time() - 3600);
17. Which PHP function checks whether a cookie exists?
• A. isset()
• B. cookie_exists()
• C. isset_cookie()
• D. check_cookie()
Answer: A. isset()
18. What does the time() function return in PHP?
• A. The current date and time
• B. The current timestamp
• C. The timestamp of the session start
• D. The cookie expiration time
Answer: B. The current timestamp
19. How can you prevent a session from timing out in PHP?
• A. By using session_set_timeout()
• B. By resetting session expiration periodically
• C. By storing the session in a database
• D. By extending the browser's timeout
Answer: B. By resetting session expiration periodically
20. What is a session ID in PHP?
• A. A unique identifier for each session
• B. A random number generated for each user
• C. A way to store user data
• D. A method for authentication
Answer: A. A unique identifier for each session
21. What happens if a user does not accept cookies in a browser?
• A. The user cannot access the website
• B. Cookies will be rejected and no session data will be saved
• C. The user will be redirected to a different page
• D. Cookies will be stored in the browser but never sent to the server
Answer: B. Cookies will be rejected and no session data will be saved
22. Which of the following is a characteristic of session cookies?
• A. They are stored until the user manually deletes them
• B. They are deleted once the session ends
• C. They last for a specific time duration set by the developer
• D. They are stored in the database
Answer: B. They are deleted once the session ends
23. How can you make a cookie secure?
• A. By setting the secure flag to true
• B. By encrypting the cookie value
• C. By setting the HttpOnly flag
• D. All of the above
Answer: D. All of the above
24. What is the difference between a session and a cookie?
• A. Cookies are more secure than sessions
• B. Cookies are stored on the client-side, while sessions are stored on the
server-side
• C. Sessions store data temporarily, while cookies store data permanently
• D. There is no difference
Answer: B. Cookies are stored on the client-side, while sessions are stored on the
server-side
25. What is the function of session_regenerate_id() in PHP?
• A. To regenerate the session data
• B. To change the session ID and keep the session active
• C. To regenerate session cookies
• D. To reset the session timeout
Answer: B. To change the session ID and keep the session active
26. How do you store data in a session in PHP?
• A. $_SESSION["key"] = "value";
• B. session_set("key", "value");
• C. store_session("key", "value");
• D. session_data("key", "value");
Answer: A. $_SESSION["key"] = "value";
27. Which of the following is used to check if a session is started?
• A. isset($_SESSION)
• B. session_started()
• C. check_session()
• D. session_status()
Answer: A. isset($_SESSION)
28. What is the correct way to destroy a session in PHP?
• A. unset($_SESSION); session_destroy();
• B. session_destroy();
• C. delete_session();
• D. unset($_SESSION["variable"]); session_end();
Answer: A. unset($_SESSION); session_destroy();
29. Which PHP function allows you to set the expiration date of a cookie?
• A. setcookie()
• B. cookie_set()
• C. set_expiration()
• D. expire_cookie()
Answer: A. setcookie()
30. How do you make a session cookie that expires when the browser is
closed?
• A. By not setting an expiration date
• B. By setting the expiration to 0
• C. By using time() as the expiration
• D. By setting the secure flag
Answer: A. By not setting an expiration date
31. What is the correct syntax to set a cookie that expires in 1 hour in PHP?
• A. setcookie("name", "value", time() + 3600);
• B. setcookie("name", "value", time() - 3600);
• C. setcookie("name", "value", "1 hour");
• D. cookie("name", "value", 3600);
Answer: A. setcookie("name", "value", time() + 3600);
32. How can you pass data between pages using sessions in PHP?
• A. By using $_GET variables
• B. By using $_SESSION variables
• C. By using cookies
• D. By using hidden form fields
Answer: B. By using $_SESSION variables
33. Which of the following is true about the HttpOnly flag in cookies?
• A. It makes the cookie accessible via JavaScript
• B. It prevents the cookie from being accessed by client-side scripts
• C. It makes the cookie expire immediately
• D. It makes the cookie visible to the user
Answer: B. It prevents the cookie from being accessed by client-side scripts
34. What does the session_regenerate_id() function do?
• A. Changes the session data
• B. Creates a new session variable
• C. Changes the session ID while preserving the session data
• D. Ends the current session and starts a new one
Answer: C. Changes the session ID while preserving the session data
35. Which of the following is NOT a feature of session management in PHP?
• A. Session data can be stored on the server
• B. Sessions can store complex data like arrays
• C. Sessions work without the user’s browser storing any data
• D. Cookies are used to store session data on the server
Answer: D. Cookies are used to store session data on the server
36. How can you make a cookie available only on a specific path?
• A. By setting the path parameter in setcookie()
• B. By using a session variable
• C. By setting the domain parameter
• D. By setting the expire parameter
Answer: A. By setting the path parameter in setcookie()
37. How do you secure a cookie from being modified by the user?
• A. By setting the HttpOnly flag
• B. By encrypting the cookie value
• C. By setting the secure flag
• D. All of the above
Answer: D. All of the above
38. What happens if session_start() is called after HTML output is sent?
• A. It will generate a warning and fail to start the session
• B. It will ignore the session_start() command
• C. It will create a new session
• D. It will delete the session
Answer: A. It will generate a warning and fail to start the session
39. What does the secure flag do when set for a cookie?
• A. It ensures the cookie is only sent over HTTPS connections
• B. It makes the cookie encrypted
• C. It makes the cookie accessible only to the server
• D. It prevents the cookie from being deleted
Answer: A. It ensures the cookie is only sent over HTTPS connections
40. What is the main difference between $_SESSION and $_COOKIE?
• A. $_SESSION stores data on the client side, $_COOKIE stores data on
the server side
• B. $_SESSION is temporary, $_COOKIE is permanent
• C. $_COOKIE stores data temporarily, $_SESSION stores data
permanently
• D. There is no difference
Answer: B. $_SESSION is temporary, $_COOKIE is permanent
41. How do you prevent a session from timing out?
• A. Use session_set_timeout()
• B. Reset session variables regularly
• C. Increase the session timeout in php.ini
• D. Both B and C
Answer: D. Both B and C
42. Which PHP function sets a secure cookie?
• A. set_secure_cookie()
• B. setcookie() with secure flag
• C. cookie_set()
• D. secure_cookie()
Answer: B. setcookie() with secure flag
43. How can you force PHP to delete a session cookie?
• A. By calling session_unset() and session_destroy()
• B. By setting session.cookie_lifetime to 0
• C. By calling setcookie() with the expiration time in the past
• D. By changing the session ID
Answer: C. By calling setcookie() with the expiration time in the past
44. What is stored in a PHP session by default?
• A. User preferences
• B. Session ID
• C. Variables like $_SESSION
• D. All data sent from the browser
Answer: C. Variables like $_SESSION
45. What does session_destroy() do?
• A. Destroys all session variables
• B. Deletes the session cookie from the browser
• C. Ends the current session
• D. All of the above
Answer: D. All of the above
46. How do you make a session more secure?
• A. Use session_regenerate_id() regularly
• B. Set a session expiration time
• C. Use session.cookie_secure and session.cookie_httponly flags
• D. All of the above
Answer: D. All of the above
47. What is the main advantage of using sessions over cookies?
• A. Sessions are stored on the server, which makes them more secure than
cookies
• B. Cookies are easier to use
• C. Sessions can store more data
• D. There is no advantage
Answer: A. Sessions are stored on the server, which makes them more secure than
cookies
48. Which of the following is true about cookies?
• A. Cookies can be accessed by both client and server
• B. Cookies are stored only on the server
• C. Cookies are not secure for storing sensitive information
• D. Both A and C
Answer: D. Both A and C
49. What happens if you set a session variable after calling session_start()?
• A. It overwrites the previous session data
• B. The new variable is added to the session
• C. The session data is lost
• D. It causes a syntax error
Answer: B. The new variable is added to the session
50. Which of the following is the correct way to check if a cookie is set in
PHP?
• A. isset($_COOKIE["cookie_name"])
• B. isset(cookie_name())
• C. check_cookie("cookie_name")
• D. $_COOKIE["cookie_name"]
Answer: A. isset($_COOKIE["cookie_name"])

5 MARKS
1. What is a session in PHP, and how does it help in maintaining state
across pages?
2. Explain how to start a session in PHP and provide an example of how to
set and retrieve session variables.
3. Describe the process of destroying a session in PHP. What are the
functions involved, and why is it necessary to destroy a session?
4. What are cookies in PHP, and how do they differ from sessions? Discuss
their advantages and disadvantages.
5. Write a PHP script to create a session, set session variables, and retrieve
them on another page.
6. How can you prevent session hijacking in PHP? Discuss methods such as
regenerating session IDs and using secure cookies.
7. What is the purpose of session_unset() and session_destroy()? Explain
with examples.
8. Explain the process of setting a cookie in PHP. What parameters are
required, and what are the default values for some of them?
9. Discuss the HttpOnly and secure flags for cookies. How do they enhance
the security of cookies?
10.Write a PHP script that checks if a session variable is set and displays a
message accordingly.
11.Describe how PHP handles session data storage and retrieval. Where is
the session data stored, and what are the implications for server-side
memory?
12.What is the role of the session_regenerate_id() function in session
management? Provide an example where it could be useful.
13.How can you delete a specific cookie in PHP? Explain the process with
an example.
14.What is the maximum size limit for a cookie in PHP? How can exceeding
this limit affect your application?
15.Describe how sessions and cookies can be used together in PHP for
managing user authentication. Explain the process from logging in to
maintaining the session.
10 MARKS
1. Explain in detail how PHP sessions work from the time they are started to
when they are destroyed. Include the functions involved, how session IDs
are handled, and the role of the session cookie.
2. Discuss the differences between session variables and cookies in PHP.
Include the storage mechanisms, security considerations, and use cases
where one might be preferred over the other.
Create a comprehensive PHP script that:
o Starts a session,
o Sets several session variables,
o Checks if the session variables are set,
o Destroys the session, and
o Displays appropriate messages at each step.**
3. Explain the security risks associated with sessions in PHP. Discuss how
to mitigate risks like session hijacking and session fixation. Include
techniques like regenerating session IDs and using secure, HttpOnly
cookies.
4. Write a PHP script that:
o Sets a cookie with a custom expiration time (e.g., 1 day),
o Checks if the cookie is set,
o Updates the cookie value after 1 hour, and
o Deletes the cookie after 2 hours.**
5. Describe the lifecycle of a session in PHP. How does PHP handle session
storage and retrieval by default? Include information about the session
cookie, session storage path, and session timeout configuration.
6. What are some potential issues with cookies (like size limit, security
concerns) in web development? Explain how to overcome these
challenges by using various cookie flags, like secure, HttpOnly, and
SameSite.
7. In a PHP application, you need to manage user preferences (such as
language and theme). Discuss how you can use both session variables and
cookies to store and retrieve these preferences. Provide code examples to
illustrate the process.
8. Explain how to use PHP sessions for user authentication. Include how to
start a session, store user credentials in session variables, and securely
destroy the session after logout. Discuss the security measures to prevent
session hijacking.
9. Write a detailed explanation of the differences between persistent and
non-persistent cookies in PHP. How would you handle scenarios where
data should be retained beyond a user’s session using persistent cookies,
and how do you set their expiration?

You might also like