0% found this document useful (0 votes)
18 views41 pages

PHP Nep Unit - 1

Uploaded by

aniketsinh2875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views41 pages

PHP Nep Unit - 1

Uploaded by

aniketsinh2875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Web Devlopment Using PHP Unit -1 M.T.

CHAUDHARY

 Web-Technologies
 Web technology refers to the tools and techniques used to build and
manage websites and web applications. It involves a combination of
programming languages, protocols, frameworks, and tools that enable
the creation, development, and maintenance of web-based content,
services, and functionalities.
 Key Components of Web Technology
1. Web Protocols:
 HTTP (HyperText Transfer Protocol): The foundation of data
communication on the web. HTTP de ines how requests and
responses are sent and received between clients (typically web
browsers) and servers.
 HTTPS (HyperText Transfer Protocol Secure): A secure
version of HTTP that uses encryption (SSL/TLS) to protect data
exchanged between the client and the server.
2. Web Browsers:
 Web browsers (such as Google Chrome, Mozilla Firefox, Safari,
and) interpret web content and display it to users. They retrieve
web pages via HTTP/HTTPS requests and render HTML, CSS,
and JavaScript.
3. Frontend Technologies (Client-Side):
 HTML (HyperText Markup Language): The standard language
used to structure content on the web. HTML provides the basic
framework for creating web pages, including text, images, links,
and multimedia.
 CSS (Cascading Style Sheets): Used to de ine the layout, design,
and appearance of web pages. CSS controls elements such as
colors, fonts, spacing, and positioning.
 JavaScript: A programming language that adds interactivity and
dynamic behavior to websites. JavaScript allows for client-side
scripting, enabling features such as form validation, animations,
and content updates without reloading the page.
4. Backend Technologies (Server-Side):
 Web Servers: A server (e.g., Apache, Nginx) is responsible for
processing requests from clients and delivering web pages or
other resources like images, videos, or data. It serves content
based on the server-side programming logic.

SHRI ADARSH BCA COLLEGE , RADHANPUR 1


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 Programming Languages: Server-side scripting languages


such as PHP, Node.js, Python, Ruby, and Java are used to
generate dynamic content, interact with databases, handle
business logic, and serve pages to the client.
 Databases: Websites often rely on databases (e.g., MySQL,
PostgreSQL, MongoDB) to store and retrieve data, such as user
information, posts, comments, or products.
5. Web Frameworks:
 Web frameworks are libraries and tools that streamline the
development of web applications. Some popular web
frameworks include:
o Frontend: React, Angular, Vue.js, Svelte.
o Backend: Django (Python), Express (Node.js), Ruby on Rails
(Ruby), Laravel (PHP).
6. APIs (Application Programming Interfaces):
 APIs enable different software applications to communicate
with each other. RESTful APIs and GraphQL are commonly used
to allow the client to interact with the server or third-party
services, such as social media platforms, payment gateways, and
cloud services.
7. Web Hosting and Deployment:
 Web hosting services provide the infrastructure to host websites
and web applications on the internet. Popular hosting platforms
include Amazon Web Services (AWS), Google Cloud, Microsoft
Azure, DigitalOcean, and specialized platforms like Heroku and
Netlify.
 Deployment tools like Docker, CI/CD pipelines, and Kubernetes
allow developers to automate the process of deploying and
managing web applications.
8. Web Security:
 Web security is critical for protecting websites and user data.
Common security measures include SSL/TLS encryption, user
authentication, data validation, and preventing attacks like
cross-site scripting (XSS), SQL injection, and cross-site request
forgery (CSRF).
 A typical web application involves communication between the
frontend (client-side) and the backend (server-side). Here’s a
simpli ied work low:

SHRI ADARSH BCA COLLEGE , RADHANPUR 2


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

User Request: The user types a URL into the browser or clicks a link.
Request Handling: The browser sends an HTTP request to the web
server.
Backend Processing: The server processes the request, potentially
querying a database, running business logic, and generating dynamic
content.
Response: The server sends the generated content back to the
browser, typically as HTML, CSS, and JavaScript.
Rendering: The browser renders the content for the user to interact
with.
 Client-side scripting
 Client-side scripting refers to scripts executed directly in a user's
web browser, rather than on the server. These scripts enable
dynamic interactions and real-time updates on web pages,
enhancing the user experience without needing to reload or
request new pages from the server.
 Client-side scripting is primarily driven by JavaScript, though
HTML and CSS also play important roles in structuring and
styling content. The key advantage of client-side scripting is its
ability to reduce server load, speed up interactions, and create
responsive, interactive web applications. Examples include
handling form validation, updating content dynamically, and
creating animations.
 Key Features of Client-Side Scripting
1. Execution in the Browser:
 Scripts run on the client (the user’s web browser), meaning that
the server is only responsible for delivering the initial web page
(HTML, CSS, and JavaScript). Once the page is loaded, all dynamic
content updates and interactions are handled directly in the
browser.
2. Interactive and Dynamic Content:
 Client-side scripting is used to change elements of the page
dynamically in response to user interactions. This can include
tasks like validating form data, displaying real-time updates, or
responding to button clicks without refreshing the page.
3. Reduced Server Load:
 Because the browser handles most of the logic and UI updates,
the server is only responsible for serving the initial content. This

SHRI ADARSH BCA COLLEGE , RADHANPUR 3


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

reduces the load on the server and minimizes network traf ic, as
only essential requests (e.g., for data) are sent.
4. Asynchronous Operations:
 JavaScript can asynchronously fetch data from the server (using
techniques like AJAX) without needing to refresh the page. This
allows for features such as in inite scrolling, live data updates,
and interactive forms.
5. Enhanced User Experience:
 The ability to manipulate the DOM (Document Object Model)
allows developers to create seamless, smooth, and engaging
experiences, like animations, real-time form validation, dynamic
content updates, and rich interactive elements.
How Client-Side Scripting Works
 Page Load:
When a user visits a webpage, the browser sends a
request to the web server. The server responds by sending
the necessary resources (HTML, CSS, JavaScript) to the
browser.
 Parsing and Rendering:
The browser parses the HTML, rendering the structure of
the page. It then applies the CSS styles, creating the visual layout.
JavaScript is executed either inline within the HTML or via
external iles.
 Event Handling:
JavaScript listens for user interactions (such as clicks,
scrolls, keypresses) using event listeners. When an event occurs,
the associated JavaScript function is triggered to perform some
action.
 DOM Manipulation:
The DOM represents the HTML structure of the page as a
tree-like structure in memory. JavaScript can interact with this
structure, modifying elements, changing styles, or
adding/removing content dynamically.
 AJAX for Asynchronous Data Fetching:
AJAX (Asynchronous JavaScript and XML) allows JavaScript to
fetch data from the server in the background without reloading the
page. This is useful for live updates, form submissions, and dynamic
content loading.

SHRI ADARSH BCA COLLEGE , RADHANPUR 4


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 Server-Side Scripting
 Server-side scripting refers to scripts that are executed on a web
server rather than in the user's web browser. When a user
requests a webpage, the server processes the server-side script,
performs any necessary operations (such as database queries,
calculations, or authentication), and then sends the results
(often in the form of HTML) to the user's browser for display.
Example Php,Node Js, Asp.net,Rubby,Java etc.
Key Characteristics of Server-Side Scripting
 Execution on the Server: The script runs on the server, which
means that the user does not see the server-side code. Only the
inal output (usually HTML) is sent to the user's browser.
 Dynamic Content Generation: Server-side scripts can generate
dynamic content based on user input, session data, or database
information. This makes it possible to personalize websites and
create interactive web applications.
 Interactivity: Server-side scripting can handle user requests,
process data, and return responses, such as retrieving
information from a database or performing calculations based
on form input.
 Security: Since the code runs on the server, it is not exposed to
the client, which makes server-side scripting more secure for
handling sensitive data, like authentication, payment
processing, and ile uploads.
How Server-Side Scripting Works
 User Request: When a user enters a URL in their browser or clicks a
link, the browser sends an HTTP request to the web server.
 Server Processing: The server processes the request and invokes the
appropriate server-side script. The script may interact with a
database, perform calculations, or generate dynamic content based on
the request.
 Database Interaction: If necessary, the server-side script can query a
database to retrieve or store information (e.g., user data, product
information, etc.).
 Response Generation: After processing, the server sends back the
resulting data (usually HTML) to the user's browser. This could include
dynamically generated web pages, such as a personalized user
dashboard or search results.

SHRI ADARSH BCA COLLEGE , RADHANPUR 5


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 User View: The browser renders the HTML received from the server
and displays the page to the user.
How Server side scripting work
Client Sends a Request
 A user interacts with a web page (e.g., submits a form, clicks a button,
or requests a URL).
 The browser sends an HTTP request to the web server hosting the
website.
Server Processes the Request
 The server identi ies the requested resource (e.g., a PHP, Python, or
Node.js script) and executes the associated server-side script.
 The script may include operations such as:
o Querying or updating a database.
o Validating user input.
o Reading or writing iles on the server.
o Generating dynamic HTML, JSON, or other content.
Interaction with a Database
 If needed, the script interacts with a database to retrieve or store data.
 For example:
o User requests their pro ile → Script queries the database for user
information.
oUser submits a comment → Script saves the comment in the
database.
Generating a Response
 The script composes a response based on the processed data.
o This could be an HTML page, JSON data for an API, or even a ile
download.
 Example:
o A login script checks the database for user credentials and either
redirects to a dashboard or shows an error message.
Sending the Response to the Client
 The server sends the generated response back to the client.
 If the response is an HTML page, it is rendered by the browser.
 If it's JSON or XML, it may be processed by client-side scripts for
further interaction.
Client Displays the Response

SHRI ADARSH BCA COLLEGE , RADHANPUR 6


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 The browser interprets and displays the content received from the
server.
 If additional resources (images, CSS, JavaScript) are required, the
browser sends subsequent requests to fetch them.
Client Side Scripting Vs Server Side Scripting
Client-side scripting Server-side scripting
Source code is visible to the user. Source code is not visible to the
user because its output
of server-sideside is an HTML
page.
Its main function is to provide Its primary function is to
the requested output to the end manipulate and provide access to
user the respective database as per
the request.
It usually depends on the In this any server-side
browser and its version. technology can be used and it
does not
depend on the client.
It runs on the user’s computer. It runs on the webserver.
There are many advantages The primary advantage is its
linked with this like faster. ability to highly customize,
response times, a more response
interactive application. requirements, access rights
based on user.
It does not provide security for It provides more security for
data data.
It is a technique used in web It is a technique that uses scripts
development in which scripts on the webserver to produce a
run on the client’s browser response that is customized for
each client’s request.
HTML, CSS, and javascript are PHP, Python, Java, Ruby are used
used.
No need of interaction with the It is all about interacting with the
server. servers.
It reduces load on processing It surge the processing load on
unit of the server. the server.

 Web browser
 A web browser is a software application that allows users to access,
retrieve, and display content on the World Wide Web, such as web

SHRI ADARSH BCA COLLEGE , RADHANPUR 7


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

pages, images, videos, and more. It acts as an interface between the


user and the internet, interpreting code from websites (HTML, CSS,
JavaScript, etc.) and rendering it into a visual and interactive form.
How a Web Browser Works
 User Request:
The user enters a URL (Uniform Resource Locator) in the
address bar (e.g., www.example.com) or clicks on a hyperlink.
The browser parses the URL to determine the protocol
(HTTP/HTTPS), the domain name (example.com), and the requested
resource (e.g., /index.html).
 Domain Name Resolution:
The browser contacts a DNS (Domain Name System) server to
resolve the domain name into an IP address.
For example, www.example.com might resolve to 192.168.1.1.
 Establishing a Connection:
The browser establishes a connection with the web server using
the IP address via the HTTP or HTTPS protocol.
For HTTPS, a secure SSL/TLS handshake is performed to encrypt
the data.
 Sending an HTTP Request:
The browser sends an HTTP request to the server, specifying the
requested resource, headers, and other details.
 Receiving an HTTP Response:
The server processes the request and sends an HTTP response
back to the browser.
The response contains:
Status code (e.g., 200 OK, 404 Not Found).
Headers (e.g., content type, cache control).
Body (e.g., HTML, JSON, or other content).
 Rendering the Content:
The browser processes the received data:
HTML: Creates the structure of the page.
CSS: Styles the page (e.g., colors, layout, fonts).
JavaScript: Executes dynamic functionality (e.g., animations,
interactivity).

SHRI ADARSH BCA COLLEGE , RADHANPUR 8


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

Additional resources (images, videos, fonts, etc.) are requested as


needed.
 Displaying the Page:
The browser renders the content and displays it to the user.
Popular Web Browsers Google Chrome, Mozilla Firefox, Safari,
Microsoft Edge, Opera.
 Web Server
 A web server is software or hardware that processes requests via the
HTTP (or HTTPS) protocol and delivers web pages, applications, or
other content to users over the internet or a local network. It serves as
the backbone of the World Wide Web, enabling the hosting and
delivery of websites.
 A web server can be:
1. Hardware: A computer that stores, processes, and serves web pages
to users.
2. Software: A program that handles HTTP requests and responses.
 Functions:
 Hosts websites and applications.
 Delivers static and dynamic content.
 Manages incoming client requests.
 Ensures secure data transmission (via HTTPS).
How a Web Server Works
 Client Sends a Request:
 A user enters a URL (e.g., https://www.example.com) or clicks a link.
 The browser generates an HTTP/HTTPS request and sends it to the
web server.
 DNS Resolution:
 The domain name in the URL is resolved to an IP address using a DNS
server.
 Establishing a Connection:
 The browser connects to the web server at the resolved IP address on
port 80 (HTTP) or port 443 (HTTPS).
 For HTTPS, an SSL/TLS handshake occurs to establish a secure
connection.
 Processing the Request:
 The web server receives the request and determines the appropriate
resource (e.g., an HTML ile, dynamic script, or API endpoint).

SHRI ADARSH BCA COLLEGE , RADHANPUR 9


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 For dynamic content, the web server interacts with an application


server or executes server-side scripts.
 Generating a Response:
 The server generates the HTTP response, which includes:
o Status code (e.g., 200 OK, 404 Not Found).
o Headers (e.g., content type, cache control).
o Body (e.g., HTML, JSON, or other content).
 Sending the Response:
 The web server sends the response back to the client (browser).
 If additional resources (e.g., images, stylesheets, or scripts) are
required, the browser sends more requests.
Components of a Web Server
 Hardware:
 A physical or virtual machine that stores and serves web content.
 Key features:
o High-speed CPUs for processing requests.
o Suf icient RAM for handling simultaneous users.
o Storage (HDDs or SSDs) to store website iles.
o Network interface for communication with clients.
 Operating System:
 The underlying system where the server software runs.
 Common OS choices:
o Linux (e.g., Ubuntu, CentOS): Preferred for its stability and
performance.
o Windows Server: Popular for enterprise environments.

 Web Server Software:


 Handles HTTP requests and responses.
 Examples:
o Apache HTTP Server: Highly con igurable and widely used.
o Nginx: Known for high performance and load balancing.
o Microsoft IIS (Internet Information Services): Integrated
with Windows Server.
o LiteSpeed: Fast and lightweight.
o Caddy: Focuses on simplicity and secure defaults.
 Server-Side Scripting Support:
 Executes scripts for generating dynamic content.
 Common scripting languages:

SHRI ADARSH BCA COLLEGE , RADHANPUR 10


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

o PHP, Python, Ruby, Node.js, Java, etc.


 Database Integration:
 Interacts with databases to retrieve or store data.
 Common databases:
o MySQL, PostgreSQL, MongoDB, Microsoft SQL Server, etc.
 Protocols:
 Supports protocols like HTTP, HTTPS, FTP, and WebSocket.
Types of Web Servers
 Static Web Servers:
 Serve pre-written, ixed content such as HTML, CSS, and JavaScript
iles.
 Fast and straightforward.
 Example: A server delivering a plain HTML page.
 Dynamic Web Servers:
 Generate content on-the- ly based on client requests or user inputs.
 Works in conjunction with:
o An application server (e.g., Django, Flask, or Rails).
o A database for dynamic data.
 Reverse Proxy Servers:
 Intercept client requests, forward them to the appropriate server, and
return the response.
 Bene its:
o Load balancing.
o Security and anonymity.

o Caching (improves performance).


 Client - Server Model.
 The client-server model in PHP is a popular architecture used for
building web applications, where the server hosts the application logic
and responds to requests sent by clients, typically web browsers or
other devices.

SHRI ADARSH BCA COLLEGE , RADHANPUR 11


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 User enters the URL(Uniform Resource Locator) of the website


or file. The Browser then requests the DNS(DOMAIN NAME
SYSTEM) Server.
 DNS Server lookup for the address of the WEB Server.
 The DNS Server responds with the IP address of the WEB Server.
 The Browser sends over an HTTP/HTTPS request to the WEB
Server’s IP (provided by the DNS server).
 The Server sends over the necessary files for the website.
 The Browser then renders the files and the website is displayed.
This rendering is done with the help of DOM (Document Object
Model) interpreter, CSS interpreter, and JS Engine collectively
known as the JIT or (Just in Time) Compilers.

Components of the Client-Server Model

1. Client:

 A user interface (e.g., a web browser, mobile app, or another service)


that sends requests to the server over HTTP or HTTPS.
 The client interacts with the server by making GET, POST, PUT,
DELETE, etc., requests.

2. Server:
 The server is responsible for processing client requests and serving
appropriate responses. This is where PHP scripts reside, along with a
web server like Apache or Nginx.
 It handles tasks such as business logic, database interactions, and
dynamic content generation.
How it Works in PHP
SHRI ADARSH BCA COLLEGE , RADHANPUR 12
Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 Client Request:
 The client sends a request (e.g., an HTTP request) to the server,
typically triggered by an action like clicking a button, submitting a
form, or loading a webpage.
 Example: GET http://example.com/get-data
 Server Response:
 The server processes the request using PHP scripts, fetches or
processes data, and sends the response back to the client.
 Example: JSON, HTML, or XML data is sent back to the client.
How PHP Fits in the Client-Server Model
 Server-Side Scripting:
 PHP runs on the server to handle incoming requests, process data, and
generate responses.
 Database Interaction:
 PHP scripts often interact with databases (like MySQL) to fetch or
store data as needed.
 Response Handling:
 PHP prepares dynamic content (HTML, JSON, etc.) that is sent to the
client.
 Middleware Role:
 PHP can also act as a middleware in APIs, interacting with other
services and forwarding the results to clients.
 History of PHP
 PHP, originally created in 1994, has grown from a
simple tool for building web pages to one of the
most widely used server-side programming
languages in the world. Here’s a timeline of its
evolution:
 1994: The Beginning

 Creator: Rasmus Lerdorf, a Danish-Canadian software engineer.


 Purpose: Rasmus created PHP to manage his personal website. It was
initially a set of Common Gateway Interface (CGI) scripts written in C.
 Original Name: "Personal Home Page Tools" (PHP Tools).
 1995: PHP 1.0
 Released as an open-source project to allow developers to use and
improve it.
 Functionality:
o Basic tools to create dynamic web applications.
o Limited features like form handling and data persistence.
 Still primarily a small, personal project at this stage.

SHRI ADARSH BCA COLLEGE , RADHANPUR 13


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 1997: PHP 2.0 (PHP/FI 2.0)


 FI: Stood for "Forms Interpreter," reflecting its enhanced ability to
work with web forms.
 Added features:
o Support for embedding dynamic content in HTML.
o Simple integration with databases.
o Improved syntax.
 Attracted more developers due to its simplicity and functionality.
 1998: PHP 3.0
 A major rewrite by Zeev Suraski and Andi Gutmans, two Israeli
developers.
 Renamed to PHP: Hypertext Preprocessor (a recursive acronym).
 Introduced a new parser, the Zend Engine, which became the core of
PHP.
 Features:
o Support for object-oriented programming.
o Modular architecture with support for extensions.
o Broader database support.
 2000: PHP 4.0
 Released using Zend Engine 1.0.
 Key improvements:
o Enhanced performance.
o Session handling.
o HTTP request/response handling.
o More robust and extensible.
 Widely adopted for building dynamic web applications.

 2004: PHP 5.0

 Powered by Zend Engine 2.0, introduced significant improvements.


 Major features:
o Comprehensive support for object-oriented programming
(OOP), including:
 Classes and objects.
 Constructors and destructors.
 Inheritance.
o Better error handling with exceptions.
o Introduction of the PHP Data Objects (PDO) extension for
database interaction.
 Became the foundation for modern PHP frameworks like Laravel,
Symfony, and CodeIgniter.

SHRI ADARSH BCA COLLEGE , RADHANPUR 14


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 2015: PHP 7.0


 A groundbreaking release after PHP 6 was abandoned due to
challenges with Unicode implementation.
 Key highlights:
o Introduced the Zend Engine 3.0, offering 2x performance
improvement over PHP 5.
o New features:
 Scalar type declarations.
 Return type declarations.
 Null coalescing operator (??).
 Spaceship operator (<=>).
o Significantly reduced memory usage.
 2020: PHP 8.0
 Powered by the JIT (Just-In-Time) compiler, which dramatically
improved performance.
 Major features:
o Union types.
o Named arguments.
o Attributes for metadata (annotations).
o Match expressions (similar to switch-case).
o Nullsafe operator (?->).
 Present Day: PHP's Role
 As of 2024, PHP remains one of the most widely used languages for
web development.
 Powers popular platforms like:
o WordPress (43% of websites globally use it).
o Drupal.
o Magento.
 Supported by a vibrant community and robust frameworks like
Laravel, Symfony, and Yii.
 Continues to evolve with a focus on performance, security, and
developer experience.

 PHP Features
 PHP (Hypertext Preprocessor) is a powerful and
versatile scripting language widely used for server-
side web development. Here are the key features of
PHP that make it popular among developers:
1. Simplicity and Ease of Use
 PHP is easy to learn, especially for beginners, due to its simple
and intuitive syntax.

SHRI ADARSH BCA COLLEGE , RADHANPUR 15


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 It integrates seamlessly with HTML, enabling developers to


embed PHP code directly within web pages.
2. Open Source
 PHP is free to use, modify, and distribute, making it accessible to
developers and organizations of all sizes.
 Supported by a large community, which constantly contributes
to updates, extensions, and frameworks.
3. Cross-Platform Compatibility
 PHP is platform-independent and can run on multiple operating
systems, including:
o Windows
o macOS
o Linux
o Unix
o Works seamlessly with most web servers, such as Apache,
Nginx, IIS, and others.
4. Server-Side Execution
 PHP scripts execute on the server, and the resulting HTML is
sent to the client’s browser.
 This ensures that sensitive business logic and database
operations remain secure on the server.
5. Dynamic Content Generation
 PHP enables the creation of dynamic web pages that can interact
with databases, fetch and display data, and personalize content
based on user inputs or preferences.
6. Database Integration
 PHP supports a wide range of databases, such as:
o MySQL
o PostgreSQL
o SQLite
o Oracle
o Microsoft SQL Server
 With extensions like PDO (PHP Data Objects) and MySQLi, developers
can easily interact with databases securely.
7. Wide Range of Built-in Functions
 PHP offers a rich set of built-in functions for:
o String manipulation
o File handling
o Session management
o Date and time operations
o Image processing (e.g., GD library)

SHRI ADARSH BCA COLLEGE , RADHANPUR 16


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

8. Extensible via Libraries and Frameworks


 PHP supports extensions and libraries for added functionality.
 Popular frameworks like Laravel, Symfony, and CodeIgniter
make development faster, secure, and scalable.
9. Object-Oriented Programming (OOP) Support
 PHP supports OOP concepts such as:
o Classes and objects
o Inheritance
o Polymorphism
o Encapsulation
o OOP enhances code reusability, scalability, and maintainability.
10. Integration with Other Technologies
 PHP can be integrated with various technologies and APIs, such
as:
o RESTful APIs
o JSON and XML parsing
o Cloud services (AWS, Google Cloud, etc.)
11.Support for Web Services
 PHP supports the development of web services using protocols
like:
o REST (Representational State Transfer)
o SOAP (Simple Object Access Protocol)
o Real-Time Applications
 PHP can be used for real-time applications like chat systems or
push noti ications with tools like WebSockets and libraries such
as Ratchet.
 PHP Comments
In PHP, comments are used to make the code more readable and
maintainable by adding explanatory notes. Comments are ignored by
the PHP interpreter during execution. PHP supports single-line, multi-
line, and documentation comments.

1. Single-Line Comments
Used for brief comments or explanations on a single line.
Syntax:

 // (C++ style comment)


 # (Unix shell style comment)

2. Multi-Line Comments

SHRI ADARSH BCA COLLEGE , RADHANPUR 17


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

Used for longer explanations or to temporarily disable a block of code.


Enclosed between /* and */
3. PHPDoc Comments
A specialized form of multi-line comments, typically used for
documentation purposes.
Enclosed between /** and */.
Supports annotations to describe classes, methods, properties,
and parameter
 PHP variable
 In PHP, variables are used to store and manipulate data. A variable in
PHP is identi ied with a dollar sign ($) followed by the variable name.
PHP variables are lexible and do not require explicit declaration of
their type, as PHP is a loosely typed language.
Features of PHP Variables
 Dynamic Typing:
 PHP automatically determines the variable's data type based on the
value assigned to it.
Example
$x = 10; // Integer
$y = "Hello"; // String
 Starts with $:

 All variable names in PHP begin with a dollar sign ($).

 Case-Sensitive:

 Variable names are case-sensitive, so $name and $Name are treated as


different variables.

 Global and Local Scope:

 Variables in PHP have different scopes (local, global, static).


 No Declaration Required:
 Variables are created automatically the moment they are assigned a
value.
Rules for Naming Variables
 Must start with a letter or an underscore (_).
 Cannot start with a number.
 Can only contain alphanumeric characters and underscores
(A-Z, a-z, 0-9, _).
 Variable names are case-sensitive.
Examples
SHRI ADARSH BCA COLLEGE , RADHANPUR 18
Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

$validVariable = "Valid";
$_another_valid_variable = 123;
$invalid-variable = "Invalid"; // Syntax Error: Hyphens are not
allowed.
 Output Variables
In PHP, you can output variables using functions or constructs
like echo, print, printf, and var_dump.
1. Using echo
A simple and widely used construct to output one or more
strings or variables.
Example
<?php
$name = "John";
$age = 25;
echo "Name: " . $name . ", Age: " . $age; // Outputs: Name: John,
Age: 25
?>
2. Using print
Similar to echo but returns a value (1), making it slightly slower.
Example
<?php
$message = "Hello, World!";
print $message; // Outputs: Hello, World!
?>
3. Using printf
Used for formatted output, allowing more control over the
output format.
Example
<?php
$name = "Alice";
$age = 30;
printf("Name: %s, Age: %d", $name, $age); // Outputs: Name:
Alice, Age: 30
?>
4. Using print_r
Outputs human-readable information about a variable
(commonly for arrays or objects).
Example
<?php
$fruits = ["Apple", "Banana", "Cherry"];

SHRI ADARSH BCA COLLEGE , RADHANPUR 19


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana


[2] => Cherry )
?>
5. Using var_dump
Displays detailed information about a variable, including its type
and value.
Example
<?php
$number = 42;
$pi = 3.14;
var_dump($number); // Outputs: int(42)
var_dump($pi); // Outputs: float(3.14)
?>
6. Using var_export
Outputs or returns a string representation of a variable in a valid
PHP code format.
Example
<?php
$data = ["name" => "Bob", "age" => 40];
var_export($data); // Outputs: array ( 'name' => 'Bob', 'age' =>
40, )
?>
 PHP Variables Scope
In PHP, variable scope refers to the context within which a variable is de ined
and accessible. PHP supports several types of scopes: local, global, static, and
superglobal.
1. Local Scope
Variables declared inside a function are local to that function
and cannot be accessed outside of it.
A local variable is created when the function is called and
destroyed once the function execution is complete.
<?php
function localScopeExample() {
$localVar = "I'm local!";
echo $localVar; // Outputs: I'm local!
}

localScopeExample();
echo $localVar; // Error: Unde ined variable
?>
2. Global Scope

SHRI ADARSH BCA COLLEGE , RADHANPUR 20


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 Variables declared outside of any function are in the global scope.


 These variables cannot be accessed directly inside a function unless
specified using the global keyword or the $GLOBALS superglobal
array.
<?php
$globalVar = "I'm global!";

function globalScopeExample() {
global $globalVar; // Importing the global variable
echo $globalVar; // Outputs: I'm global!
}

globalScopeExample();
?>
<?php
$globalVar = "Accessible via \$GLOBALS";

function globalScopeExample() {
echo $GLOBALS['globalVar']; // Outputs: Accessible via $GLOBALS
}

globalScopeExample();
?>
3. Static Scope
A variable declared as static inside a function retains its value
between function calls.
 Unlike local variables, static variables are not destroyed when the
function ends. However, they are only accessible within the function
they are declared in.
<?php
function staticScopeExample() {
static $counter = 0; // Static variable
$counter++;
echo $counter . "\n";
}

staticScopeExample(); // Outputs: 1
staticScopeExample(); // Outputs: 2
staticScopeExample(); // Outputs: 3
?>
4. Superglobal Scope

SHRI ADARSH BCA COLLEGE , RADHANPUR 21


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

Superglobals are predefined variables in PHP that are always


accessible, regardless of scope.
Examples: $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER,
$_FILES, $_ENV, and $GLOBALS.

 PHP Data Types


1. Scalar Data Types
 Scalar types represent a single value.
a) Integer
 Represents whole numbers (positive, negative, or zero)
without decimals.
 Example: 1, -42, 1000.
 Range: Platform-dependent (commonly -2³¹ to 2³¹-1 for
32-bit systems and -2⁶³ to 2⁶³-1 for 64-bit systems).
b) Float (or Double)
Represents numbers with a decimal point or in exponential form.
Example: 3.14, 1.2e3 (1.2 × 10³).
c) String
 Represents a sequence of characters enclosed in single (') or
double (") quotes.
 Strings in double quotes support variable interpolation and
escape sequences, while single quotes do not.
d) Boolean
 Represents two possible values: true or false.
 Used for logical operations and conditional statements.

2. Compound Data Types


 Compound types can hold multiple values or more
complex structures.
a) Array
 Used to store multiple values in one variable.
 Types of arrays:
o Indexed: Uses numeric keys.
o Associative: Uses named keys.
o Multidimensional: Arrays of arrays.
b) Object
 Represents instances of user-de ined classes.
 Allows storing data and methods speci ic to an object.
3.Special Data Types

SHRI ADARSH BCA COLLEGE , RADHANPUR 22


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

a) NULL
 Represents a variable with no value or an explicitly assigned null
value.
b) Resource
 Refers to an external resource like a ile handle or database
connection.
 Typically created using special functions (e.g., fopen,
mysqli_connect).
 Type Casting
 PHP allows converting variables from one data type to another.
PHP is a loosely typed language, so variables are automatically
assigned data types based on their values.
<?php
$var = 10; // Integer
$var = "PHP"; // String
$var = true; // Boolean
?>
 Typecasting in PHP is the process of converting a variable
from one data type to another. Since PHP is a loosely typed
language, it automatically converts variables to the
required data type when performing certain operations.
However, there are times when you might need to
explicitly change the type of a variable using typecasting.
 Syntax for Typecasting
 The syntax for typecasting in PHP involves placing the
desired data type in parentheses before the variable or
value:
 $new_variable = (type) $variable;
Examples of Typecasting
1. Integer Casting
 Converts a variable to an integer.
<?php
$ loat = 10.5;
$integer = (int)$ loat; // Explicitly casting to an integer
echo $integer; // Outputs: 10
?>
2. Float Casting
 Converts a variable to a loating-point number.
<?php
$string = "3.14";
$ loat = ( loat)$string; // Casting to loat

SHRI ADARSH BCA COLLEGE , RADHANPUR 23


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

var_dump($ loat); // Outputs: loat(3.14)


?>
3. String Casting
 Converts a variable to a string.
<?php
$number = 123;
$string = (string)$number; // Casting to string
var_dump($string); // Outputs: string(3) "123"
?>
 PHP Operators:
 PHP provides arithmetic operators to perform
mathematical operations on numbers. These operators
work with integer, loat, or numeric string data types.
 Arithmetic Operators
1. Addition (+)
 Adds two numbers together.
<?php
$a = 10;
$b = 20;
$result = $a + $b;
echo $result; // Outputs: 30
?>
2. Subtraction (-)
 Subtracts one number from another.
<?php
$a = 20;
$b = 5;
$result = $a - $b;
echo $result; // Outputs: 15
?>
3. Multiplication (*)
 Multiplies two numbers.
<?php
$a = 4;
$b = 5;
$result = $a * $b;
echo $result; // Outputs: 20
?>
4. Division (/)
 Divides one number by another.
<?php

SHRI ADARSH BCA COLLEGE , RADHANPUR 24


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

$a = 15;
$b = 3;
$result = $a / $b;
echo $result; // Outputs: 5
?>
5. Modulus (%)
 Returns the remainder after dividing one number by
another.
<?php
$a = 10;
$b = 3;
$result = $a % $b;
echo $result; // Outputs: 1
?>
6. Exponentiation (**)
 Raises one number to the power of another.
<?php
$a = 2;
$b = 3;
$result = $a ** $b;
echo $result; // Outputs: 8 (2³)
?>
 Assignment operators
 Assignment operators in PHP are used to assign values to
variables. The simplest assignment operator is the equals
sign (=), but PHP also provides compound assignment
operators that combine arithmetic or bitwise operations
with assignment.
 Examples of Compound Assignment Operators
1. Addition Assignment (+=)
<?php
$x = 10;
$x += 5; // Equivalent to $x = $x + 5
echo $x; // Outputs: 15
?>
2. Subtraction Assignment (-=)
<?php
$x = 10;
$x -= 3; // Equivalent to $x = $x - 3
echo $x; // Outputs: 7
?>

SHRI ADARSH BCA COLLEGE , RADHANPUR 25


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

3. Multiplication Assignment (*=)


<?php
$x = 4;
$x *= 3; // Equivalent to $x = $x * 3
echo $x; // Outputs: 12
?>
4. Division Assignment (/=)
<?php
$x = 20;
$x /= 4; // Equivalent to $x = $x / 4
echo $x; // Outputs: 5
?>
5. Modulus Assignment (%=)
<?php
$x = 10;
$x %= 3; // Equivalent to $x = $x % 3
echo $x; // Outputs: 1
?>
6. Exponentiation Assignment (**=)
<?php
$x = 2;
$x **= 3; // Equivalent to $x = $x ** 3
echo $x; // Outputs: 8
?>
7. Concatenation Assignment (.=)
<?php
$text = "Hello";
$text .= " World"; // Equivalent to $text = $text . " World"
echo $text; // Outputs: Hello World
?>
 Comparison operators
1. Equal (==)
<?php
$a = 5;
$b = "5";
var_dump($a == $b); // Outputs: bool(true) (values are equal,
type conversion occurs)
?>
2. Identical (===)
<?php
$a = 5;

SHRI ADARSH BCA COLLEGE , RADHANPUR 26


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

$b = "5";
var_dump($a === $b); // Outputs: bool(false) (values are equal,
but types are different)
?>
3. Not Equal (!= or <>)
<?php
$a = 5;
$b = 10;
var_dump($a != $b); // Outputs: bool(true) (values are not
equal)
?>
4. Not Identical (!==)
<?php
$a = 5;
$b = "5";
var_dump($a !== $b); // Outputs: bool(true) (values are equal,
but types are different) ?>
5. Less Than (<)
<?php
$a = 3;
$b = 7;
var_dump($a < $b); // Outputs: bool(true)
?>
6. Greater Than (>)
<?php
$a = 10;
$b = 7;
var_dump($a > $b); // Outputs: bool(true)
?>
7. Spaceship Operator (<=>)
 The spaceship operator is used to compare two values. It
returns:

 -1 if the left value is less than the right value.


 0 if the two values are equal.
 1 if the left value is greater than the right value.

<?php
echo 5 <=> 10; // Outputs: -1 (5 is less than 10)
echo 10 <=> 10; // Outputs: 0 (10 is equal to 10)
echo 15 <=> 10; // Outputs: 1 (15 is greater than 10)

SHRI ADARSH BCA COLLEGE , RADHANPUR 27


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

?>
 Increment/Decrement operators
 PHP provides increment and decrement operators to increase
or decrease a variable's value by 1. These operators are
commonly used in loops, counters, and arithmetic operations.
1. Pre-Increment (++$x)
 Increments the value of $x before it is used.
<?php
$x = 5;
echo ++$x; // Outputs: 6
echo $x; // Outputs: 6
?>
2. Post-Increment ($x++)
 Returns the current value of $x, then increments it.
<?php
$x = 5;
echo $x++; // Outputs: 5
echo $x; // Outputs: 6
?>
3. Pre-Decrement (--$x)
 Decrements the value of $x before it is used.
<?php
$x = 5;
echo --$x; // Outputs: 4
echo $x; // Outputs: 4
?>
4. Post-Decrement ($x--)
 Returns the current value of $x, then decrements it.
<?php
$x = 5;
echo $x--; // Outputs: 5
echo $x; // Outputs: 4
?>
 Logical operators
1. Logical AND (&& or and)
 The AND operator returns true only if both conditions are true.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 && $y < 30); // Outputs: bool(true)
var_dump($x > 15 && $y < 30); // Outputs: bool(false)

SHRI ADARSH BCA COLLEGE , RADHANPUR 28


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

?>
2. Logical OR (|| or or)
 The OR operator returns true if at least one condition is true.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 || $y < 15); // Outputs: bool(true)
var_dump($x > 15 || $y < 15); // Outputs: bool(false)
?>
3. Logical NOT (!)
 The NOT operator negates the result of a condition. It returns
true if the condition is false, and false if the condition is true.
<?php
$x = 10;
var_dump(!($x > 5)); // Outputs: bool(false)
var_dump(!($x < 5)); // Outputs: bool(true) ?>
4. Logical XOR (xor)
 The XOR operator returns true if exactly one of the conditions is
true, but not both.
<?php
$x = 10;
$y = 20;
var_dump($x > 5 xor $y < 10); // Outputs: bool(true)
var_dump($x > 5 xor $y < 30); // Outputs: bool(false)
?>
 String operators
 In PHP, string operators are used to manipulate and combine
strings. PHP provides two primary string operators:
1. Concatenation Operator (.)
 The concatenation operator (.) is used to join two or more
strings into a single string.
<?php
$greeting = "Hello";
$name = "John";
$message = $greeting . " " . $name . "!";
echo $message; // Outputs: Hello John!
?>
In this example:
The strings "Hello", " ", "John", and "!" are concatenated into one
string: "Hello John!".
2. Concatenation Assignment Operator (.=)

SHRI ADARSH BCA COLLEGE , RADHANPUR 29


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 The concatenation assignment operator (.=) appends a string to


an existing string and updates the variable.
<?php
$message = "Hello";
$message .= " John";
$message .= "!";
echo $message; // Outputs: Hello John!
?>
In this example:
The first line initializes $message as "Hello".
The second line appends " John" to $message, making it "Hello
John".
The third line appends "!", resulting in "Hello John!".
3. Conditional assignment operators
1. Ternary Operator (?:)
 The ternary operator is a shorthand for an if-else statement. It
evaluates a condition and returns one of two values based on
whether the condition is true or false.
<?php
$age = 20;
// Assign a value based on a condition
$canVote = ($age >= 18) ? "Yes" : "No";
echo $canVote; // Outputs: Yes
?>
If $age >= 18 evaluates to true, $canVote is assigned "Yes".
 Otherwise, it is assigned "No".
2. Null Coalescing Operator (??)
 The null coalescing operator checks if a variable is set and not
null. If it is, it returns the variable's value; otherwise, it returns a
default value. This operator is useful for handling unde ined or
null values.
<?php
$name = null;
// Assign a default value if $name is null
$result = $name ?? "Guest";
echo $result; // Outputs: Guest
?>
If $name is null, $result is assigned "Guest".
If $name has a value, $result is assigned that value.
 Bitwise operators

SHRI ADARSH BCA COLLEGE , RADHANPUR 30


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 Bitwise operators in PHP are used to manipulate data at the


binary level. These operators treat their operands as a series of
binary digits (bits) rather than decimal or other numerical
representations. Bitwise operations are particularly useful for
tasks like permissions management, lags, masks, and low-level
data manipulation.
1. Bitwise AND (&)
 The result has 1 where both corresponding bits in the operands
are 1.
<?php
$a = 5; // Binary: 0101
$b = 3; // Binary: 0011
$result = $a & $b; // Binary: 0001
echo $result; // Outputs: 1
?>
2. Bitwise OR (|)
 The result has 1 where at least one of the corresponding bits in
the operands is 1.
<?php
$a = 5; // Binary: 0101
$b = 3; // Binary: 0011
$result = $a | $b; // Binary: 0111
echo $result; // Outputs: 7
?>
3. Bitwise XOR (^)
 The result has 1 where the corresponding bits in the operands
are different.
<?php
$a = 5; // Binary: 0101
$b = 3; // Binary: 0011
$result = $a ^ $b; // Binary: 0110
echo $result; // Outputs: 6
?>
4. Bitwise NOT (~)
 The result is the complement of the operand. Each bit is inverted
(1 becomes 0, and 0 becomes 1). Note that this operation also
lips the sign of the number because of PHP's representation of
integers using two's complement.
<?php
$a = 5; // Binary: 0101
$result = ~$a; // Binary: ...11111010 (inverts all bits)

SHRI ADARSH BCA COLLEGE , RADHANPUR 31


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

echo $result; // Outputs: -6


?>
5. Left Shift (<<)
 Shifts the bits of the number to the left by the speci ied number
of positions. Each left shift effectively multiplies the number by
<?php
$a = 5; // Binary: 0101
$result = $a << 1; // Binary: 1010
echo $result; // Outputs: 10
?>
6. Right Shift (>>)
<?php
$a = 5; // Binary: 0101
$result = $a >> 1; // Binary: 0010
echo $result; // Outputs: 2
?>
 Operator Precedence and Associativity
 In PHP, operator precedence determines the order in which
operators are evaluated in an expression. Operators with higher
precedence are evaluated before those with lower precedence.
Associativity determines the order of evaluation when two
operators have the same precedence: left-to-right or right-to-
left.
Precedence Operators Associativity Description
1 clone, new Right-to-Left Clone object,
create new
object
2 ** Right-to-Left Exponentiation
3 ++, -- None (Unary) Pre-increment,
Pre-decrement
4 ~, (int), ( loat), Right-to-Left Bitwise NOT,
(string), (array), Type casting
(bool), (unset)
5 @ Left-to-Right Error control
6 *, /, % Left-to-Right Multiplication,
Division,
Modulus
7 +, -, . Left-to-Right Addition,
Subtraction,
Concatenation

SHRI ADARSH BCA COLLEGE , RADHANPUR 32


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

8 <<, >> Left-to-Right Bitwise shift left,


right
9 <, <=, >, >= Non-associative Comparison
10 ==, !=, ===, !==, Non-associative Equality,
<=> Identity,
Comparison

Associativity in PHP

 When operators share the same precedence, their associativity


decides the order of execution.

Left-to-Right Associativity: Operators are evaluated from left to


right.
Example: +, -, *, /, ., etc.
 Right-to-Left Associativity: Operators are evaluated from right to
left.
Example: =, +=, ? :, **, ??, etc.
 Non-Associative: No evaluation order; combining them directly will
result in an error.
Example: Relational operators like <, >, <=, >=.
Examples
1. Precedence Example
<?php
$result = 5 + 3 * 2; // Multiplication (*) has higher precedence than
addition (+)
echo $result; // Outputs: 11
?>
2. Associativity Example
<?php
$result = 10 - 5 - 2; // Left-to-right associativity for subtraction (-)
echo $result; // Outputs: 3
?>
3. Right-to-Left Associativity Example
<?php
$a = $b = $c = 10; // Right-to-left associativity for assignment (=)
echo $a, $b, $c; // Outputs: 101010
?>
 PHP variable handling functions
PHP offers a wide range of built-in functions for handling
variables. These functions help in checking, manipulating, and

SHRI ADARSH BCA COLLEGE , RADHANPUR 33


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

managing variables ef iciently. Here's a categorized list of common


PHP variable handling functions:
1. Variable Checking Functions
 These functions determine the type or state of a variable.
 isset($var): Checks if a variable is set and is not NULL.
 empty($var): Checks if a variable is empty (0, false, '', null, or an
empty array).
 is_null($var): Checks if a variable is NULL.
 is_bool($var): Checks if a variable is a boolean.
 **is_int($var) / **is_integer($var) / is_long($var): Checks if a variable
is an integer.
 **is_ loat($var) / **is_double($var) / is_real($var): Checks if a
variable is a loating-point number.
 is_numeric($var): Checks if a variable is numeric.
 is_string($var): Checks if a variable is a string.
 is_array($var): Checks if a variable is an array.
 is_object($var): Checks if a variable is an object.
 is_resource($var): Checks if a variable is a resource.
 is_scalar($var): Checks if a variable is a scalar (int, loat, string, or
boolean).
 is_callable($var): Checks if a variable is callable as a function.
 gettype($var): Returns the type of a variable as a string.
2.Variable Manipulation Functions
 These functions help modify or retrieve speci ic properties of
variables.
 var_dump($var): Dumps detailed information about a variable,
including its type and value.
 print_r($var): Prints human-readable information about a variable
(useful for arrays and objects).
 serialize($var): Serializes a variable into a string.
 unserialize($string): Converts a serialized string back into a variable.
 get_de ined_vars(): Returns an array of all de ined variables in the
current scope.
 compact($var1, $var2, ...): Creates an array from variables and their
values.
 extract($array): Imports variables from an array into the current
symbol table.

SHRI ADARSH BCA COLLEGE , RADHANPUR 34


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 array_key_exists($key, $array): Checks if a speci ied key exists in an


array.
 in_array($needle, $haystack): Checks if a value exists in an array.
3.Variable Scope and References

 unset($var): Unsets a variable, making it undefined.


 global $var: Declares a global variable to access it in a function.
 static $var: Declares a static variable that retains its value across
function calls.

 PHP Conditional statements


PHP provides powerful and lexible conditional statements
using if-else. These allow you to execute speci ic blocks of code based
on certain conditions. Here's a breakdown of how to use if-else
statements effectively in PHP:
 Basic Syntax
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote."; }
If-Else If-Else Structure
Used for multiple conditions.
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the above conditions are true
}
Example:
$marks = 85;
if ($marks >= 90) {
echo "Grade: A+";
} elseif ($marks >= 75) {

SHRI ADARSH BCA COLLEGE , RADHANPUR 35


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

echo "Grade: A";


} elseif ($marks >= 50) {
echo "Grade: B";
} else {
echo "Grade: F";
}
Nested If Statements
 You can nest one if statement inside another.
if (condition1) {
if (condition2) {
// Code to execute if both condition1 and condition2 are
true
}
}
$age = 25;
$citizen = true;
if ($age >= 18) {
if ($citizen) {
echo "You are eligible to vote.";
} else {
echo "You must be a citizen to vote.";
}
} else {
echo "You are not old enough to vote.";
}
 switch statement
The switch statement in PHP is a control structure that is used
to execute one block of code among many alternatives. It is especially
useful when you have multiple possible values for a single variable and
need to execute different blocks of code for each value.
 Syntax
switch (expression) {
case value1:
// Code to execute if expression == value1
break;
case value2:
// Code to execute if expression == value2
break;
// Add more cases as needed
default:
// Code to execute if no cases match

SHRI ADARSH BCA COLLEGE , RADHANPUR 36


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

break;
}
 Key Points
 The expression is evaluated once.
 Each case checks whether the expression matches the given
value.
 The break statement exits the switch block; otherwise,
execution continues to the next case (this is called fall-through
behavior).
 The default block is optional and is executed if none of the case
values match.
Example: Simple Calculator
$operation = '+';
$num1 = 10;
$num2 = 5;
switch ($operation) {
case '+':
echo $num1 + $num2;
break;
case '-':
echo $num1 - $num2;
break;
case '*':
echo $num1 * $num2;
break;
case '/':
if ($num2 != 0) {
echo $num1 / $num2;
} else {
echo "Cannot divide by zero.";
}
break;
default:
echo "Invalid operation.";
break;
}
 PHP Loops and branching statements
1. while

SHRI ADARSH BCA COLLEGE , RADHANPUR 37


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 The while statement in PHP is used to execute a block of


code repeatedly as long as a speci ied condition evaluates
to true. It's one of the simplest looping structures in PHP.
Example: Simple Counter
$i = 1;
while ($i <= 5) {
echo "The number is: $i<br>";
$i++;
}
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
2. do...while
 The do...while statement in PHP is a looping structure that
ensures the block of code executes at least once,
regardless of the condition. After the irst iteration, the
condition is evaluated to determine whether the loop
should continue.
 Key Difference from while
 A while loop checks the condition before executing the
block, so it may not run even once if the condition is false
initially.
 A do...while loop guarantees at least one execution of the
block, regardless of the initial condition.
Example: Basic Counter
$i = 1;
do {
echo "The number is: $i<br>";
$i++;
} while ($i <= 5);
Output:
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
3. for

SHRI ADARSH BCA COLLEGE , RADHANPUR 38


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

 The for loop in PHP is a powerful and commonly used


looping construct that repeats a block of code for a
speci ied number of iterations. It is particularly useful
when the number of iterations is known beforehand.
 Syntax
for (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}
 initialization: Executes once at the beginning of the loop.
Typically used to set a counter variable.
 condition: Evaluated before each iteration. If true, the
loop executes; if false, the loop stops.
 increment/decrement: Executes after each iteration.
Typically used to update the counter variable.
Example: Basic Counter
for ($i = 1; $i <= 5; $i++) {
echo "The number is: $i<br>";
}
Output
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
4. foreach
 The foreach loop in PHP is a convenient way to iterate
over arrays or objects. It simpli ies working with
collections of data by automatically handling the iteration
process.
 Syntax
foreach ($array as $value) {
// Code to execute for each value
}
 $array: The array or object to iterate over.
 $value: Represents the current value in the array during
each iteration.
 Syntax with Keys
If you also want to access the keys of the array:
foreach ($array as $key => $value) {
// Code to execute for each key-value pair }
$key: Represents the current key in the array.
SHRI ADARSH BCA COLLEGE , RADHANPUR 39
Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

Examples
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "Color: $color<br>";
}
Output:
Color: Red
Color: Green
Color: Blue
5. Break statement
 The break statement in PHP is used to terminate a loop or
switch statement immediately, regardless of the iteration
or condition. It is useful for prematurely stopping a loop
or exiting a switch case.
Usage Scenarios
1. In Loops
 The break statement stops the current loop and moves
control to the code immediately following the loop.
Example: Stopping a Loop
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break; // Exit the loop when $i equals 5
} echo "Number: $i<br>"; }
Output
Number: 1
Number: 2
Number: 3
Number: 4
6. Continue statement
 The continue statement in PHP is used to skip the rest of
the current iteration of a loop and proceed to the next
iteration. It is commonly used when a certain condition is
met, and you want to skip executing the remaining code
within the loop body for that iteration.
1. In Loops
 The continue statement skips the rest of the loop's code
for the current iteration and jumps to the next iteration.
Example: Skipping Speci ic Iterations
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue; // Skip the iteration when $i equals 3

SHRI ADARSH BCA COLLEGE , RADHANPUR 40


Web Devlopment Using PHP Unit -1 M.T.CHAUDHARY

} echo "Number: $i<br>"; }


Output
Number: 1 Number: 2 Number: 4 Number: 5

SHRI ADARSH BCA COLLEGE , RADHANPUR 41

You might also like