0% found this document useful (0 votes)
3 views42 pages

Web Tech Notes

The document is an introduction to PHP, covering its history, installation, and basic development concepts. It explains PHP's uses in server-side scripting, command-line scripting, and client-side applications, along with its evolution through various versions. Additionally, it outlines PHP's lexical structure, including identifiers, keywords, and data types, essential for writing valid PHP code.

Uploaded by

gsharan4890
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)
3 views42 pages

Web Tech Notes

The document is an introduction to PHP, covering its history, installation, and basic development concepts. It explains PHP's uses in server-side scripting, command-line scripting, and client-side applications, along with its evolution through various versions. Additionally, it outlines PHP's lexical structure, including identifiers, keywords, and data types, essential for writing valid PHP code.

Uploaded by

gsharan4890
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

1

Department of Computer applications


Subject Name: WEB TECHNOLOGY
Subject Code : 241S32
Class: II\ [Link] CA

UNIT I
Introducing PHP – Basic development Concepts – Creating first PHP Scripts – Using Variable and Operators
– Storing Data in variable – Understanding Data types – Setting and Checking variables Data types – Using
Constants – Manipulating Variables with Operators.

➢ Introduction to PHP :
PHP is a simple yet powerful language designed for creating HTML content. This chapter covers essential
background on the PHP language. It describes the nature and history of PHP, which platforms it runs on, and
how to configure it..
What does PHP do ?
PHP (Hypertext Preprocessor) is a versatile scripting language primarily used for web development, but it
can indeed be used in multiple ways. Here's a brief overview of the three primary ways PHP can be utilized :
1. Server-Side Scripting : Server-side scripting is the most common and traditional use of PHP. In this
context, PHP is embedded within HTML to create dynamic web pages. When a user requests a PHP page from
a web server, the server processes the PHP code, which may interact with databases, files, or other data sources,
and generates HTML content to be sent to the user's web browser.
2. Command-Line Scripting : PHP can also be used for command-line scripting, allowing developers to
create scripts that run on a server or a local computer without the need for a web server or browser. These
scripts can perform various tasks, such as data processing, file manipulation, and system administration.
3. Client-Side GUI Applications : While PHP is not commonly used for creating standalone client-side
graphical user interfaces (GUI), you can use PHP in combination with other technologies to develop client-
side web applications. PHP can generate HTML, CSS, and JavaScript code, which can be rendered in the
user's web browser. These applications can provide interactive and responsive user interfaces. While the bulk
of the processing still happens on the server side, JavaScript plays a more prominent role for client-side
interactivity.
➢ A Brief History of PHP :
PHP history dates back to the early days of the web, and it has gone through several significant milestones.
Here's a brief history of PHP :
1. Creation of PHP/FI (1994): PHP originated in 1994 when Rasmus Lerdorf, a programmer, created a
set of Perl scripts to track visits to his online resume. He later expanded it to handle form data and interact
with databases, naming it "Personal Home Page/Forms Interpreter" or PHP/FI. It was more of a collection of
tools than a programming language.
2. Introduction of PHP 2.0 (1995): PHP/FI was further developed, and in 1995, PHP 2.0 was released.
This version included more advanced features, better support for web forms, and could communicate with
various databases.
3. Birth of PHP 3.0 (1998): PHP 3.0, released in 1998, marked a significant milestone. It was a complete
rewrite of the PHP codebase and introduced the parser written in C, making it more efficient and faster. PHP
3.0 also added support for various databases and improved support for different web servers.
2

4. PHP 4.0 (2000): PHP 4.0, released in 2000, was a major step forward in PHP's evolution. It included
enhanced support for object-oriented programming (OOP), better performance, and added numerous features.
PHP was now recognized as a full-fledged scripting language suitable for building dynamic websites.
5. PHP 5.0 (2004): PHP 5.0, released in 2004, brought even more significant changes. It introduced the
Zend Engine 2, which greatly improved performance and added features like exception handling, and support
for OOP was significantly enhanced with the introduction of classes and interfaces.
6. PHP 5.3 (2009): PHP 5.3, released in 2009, included features such as namespaces and late static binding,
which made it easier to manage large codebases and improve code organization.
7. PHP 5.4 (2012): PHP 5.4, released in 2012, focused on performance improvements, and it introduced
short array syntax, traits, and improvements in syntax and language features.
8. PHP 7.0 (2015): PHP 7.0 was a ground-breaking release in terms of performance. It introduced the Zend
Engine 3, which significantly improved PHP's execution speed. The update also included scalar type
declarations, the spaceship operator, and the null coalescing operator.
9. PHP 7.4 (2019): PHP 7.4 brought features like arrow functions, typed properties, and improved
performance.
10. PHP 8.0 (2020): PHP 8.0 introduced several new features, including the JIT (Just-In-Time) compiler,
union types, and match expressions. It further enhanced performance and language capabilities.
PHP continues to evolve, with regular updates and improvements. It remains a widely used language for
web development, powering countless websites and web applications. Its open-source nature and active
community make it a versatile and robust choice for developers around the world.
➢ Installing PHP :
As was mentioned above, PHP is available for many operating systems and platforms. Therefore, we are
encouraged to go to this URL to find the environment that most closely fits the one we will be using and
follow the appropriate instructions. From time to time, we may also want to change the way PHP is configured.
To do that we will have to change the PHP configuration file and restart our Apache server. Each time we
make a change to PHP’s environment, we will have to restart the Apache server in order for those changes to
take effect. PHP’s configuration settings are maintained in a file called [Link]. The settings in this file control
the behaviour of PHP features, such as session handling and form processing.
➢ A Walk Through PHP :
PHP pages are generally HTML pages with PHP commands embedded in them.
Example 1-1. hello_world.php
<html>
<head>
<title> Look out World </title>
</head>
<body>
<?php echo “Hello, World!”; ?>
</body>
</html>
Save the contents of Example 1-1 to a file, hello_world.php, and point your browser to it. The PHP echo
command produces output (the string “Hello, world!” in this case) inserted into the HTML file. In this
example, the PHP code is placed between the tags.
➢ Procedure of Configure PHP on windows :
Configuring PHP on a Windows system involves several steps to set up the PHP interpreter and integrate it
with a web server like Apache or Nginx. Here is a step-by-step procedure to configure PHP on Windows:
3

1. Download PHP:
Visit the PHP official website ([Link] and download the latest stable version
of PHP for Windows. Choose the thread-safe version.2. Install PHP: Extract the downloaded PHP zip archive
to a directory on your system (e.g., C:\PHP).
3. Configure [Link]:
Inside the PHP directory, locate the [Link]-development file and make a copy of it named [Link]. This
is the configuration file for PHP. Open [Link] with a text editor and configure PHP settings according to
your needs. For example, you can set the time zone, enable extensions, and adjust memory limits. Be sure to
save the changes.
4. Add PHP to PATH (Optional but recommended) :
To use PHP from the command line globally, you can add the PHP directory to your system's PATH
environment variable. This step is optional but makes it easier to run PHP scripts from the command line.
5. Web Server Configuration:
If you don't have a web server installed, you can use the built-in web server provided by PHP for
development purposes by running php -S localhost:80 in the directory containing your PHP files. For a
production setup, you would typically use Apache or Nginx.
6. Configure Web Server:
If you're using Apache:
Download and install Apache from the official website ([Link]
Open the Apache [Link] file (usually located in the conf directory) and add the following
lines to load the PHP module :
LoadModule php_module "C:/PHP/php8apache2_4.dll"
AddHandler application/x-httpd-php .php
PHPIniDir "C:/PHP"
If you're using Nginx, you'll need to configure FastCGI to work with PHP. This involves modifying your
Nginx configuration file to pass PHP requests to the FastCGI server. You'll also need to specify the PHP
interpreter's location.
7. Test PHP:
Create a simple PHP script (e.g., [Link]) and place it in your web server's document root (e.g., htdocs
for Apache).
In the PHP script, you can use the phpinfo() function to display PHP information.
For Example:
<?php
phpinfo();
?>Access the script in your web browser (e.g., [Link] to check if PHP is configured correctly.
8. Troubleshooting:
If you encounter any issues, check the error logs of both PHP and your web server for details. Once you
have successfully configured PHP on Windows, you can start developing and running PHP web applications.
Be sure to keep PHP and your web server software up to date for security and performance reasons.
Language Basics
➢ Lexical Structure :
The lexical structure in PHP refers to the set of rules and conventions that dictate how the PHP source code
should be written and structured. Understanding PHP's lexical structure is crucial for writing valid and
readable code. Here are some key aspects of PHP's lexical structure:
1. Case Sensitivity:
4

The names of user-defined classes and functions, as well as built-in constructs and keywords such as echo,
while, class, etc., are case-insensitive. Thus, these three lines are equivalent:
echo("hello, world"); ECHO("hello,
world");
EcHo("hello, world");
Variables, on the other hand, are case-sensitive. That is, $name, $NAME, and $NaME are three different
variables.
2. Semicolons:
Statements in PHP are terminated with a semicolon ;. Omitting the semicolon at the end of a statement
can lead to syntax errors. $variable = 42; // Valid echo "Hello, World"; // Valid
3. Whitespace:
PHP is relatively lenient when it comes to whitespace, but it's essential for code readability. You can use
spaces, tabs, and line breaks to format your code as needed.
$variable = 42; // This is well-formatted $variable=42;
// This is valid but less readable
4. Comments:
PHP supports two types of comments:
Single-line comments: These begin with // and extend to the end of the line.
Multi-line comments: These start with /* and end with */. Multi-line comments can span multiple
lines and are often used for documentation.
// This is a single-line comment
/*
This is a multi-line comment that
spans multiple lines
*/
5. Shell Style Comments :
In PHP, shell-style comments begin with # and extend to the end of the line. They are similar to single-line
comments that start with // or /* ... */ comments, but they are less common in PHP and may not be as widely
recognized or supported as // or /* ... */ comments. Here's an example of shell-style comments in PHP:
##########################################
####### This is a shell-style comment ##########
$variable = 42;
#########################################
➢ Literals :
In PHP, a literal is a notation used to represent fixed values in source code. These values are constant and don't
change during the execution of the program. PHP supports various types of literals to represent different data
types, such as integers, floating-point numbers, strings, and more.
Example : 2001 , 1.34 , “Hello World” , ‘Hi’ , true , null
5

➢ Identifiers :
In PHP, identifiers are names used to represent variables, functions, classes, and constants. Identifiers follow
specific rules and conventions, and it's important to use meaningful and consistent names in your code. Here
are the rules for creating identifiers for variable names, function names, class names, and constants
1. Variable Names :
Variable names are used to store and manipulate data in PHP. They must start with a dollar sign ($)
followed by a letter or an underscore, and can be followed by letters, numbers, and [Link] names
are case-sensitive.
Example of valid variable names:
$count;
$user_name;
$_value;
$myVariable123;
2. Function Names :
Function names in PHP are not case-sensitive, which means you can call them with different letter casing,
but it's a good practice to use lowercase letters for function names.
Function names must start with a letter or an underscore, followed by letters, numbers, and underscores.
Example of valid function
names myFunction();
process_data(); _helperFunction();
3. Class Names :
Class names in PHP are typically written in CamelCase, where the first letter of each word is capitalized,
and there are no underscores. Class names are case-sensitive.
Example of valid class names:
class MyClass {} class
UserRegistration {} class
DatabaseConnection {}
4. Constants:
Constants in PHP are typically written in uppercase letters with underscores separating words. By
convention, they are often defined at the top of a script or in a configuration file.
Constants are case-sensitive.
Example of valid constants:
define('PI', 3.14159);
define('DB_HOST',
'localhost');
define('MAX_USERS', 100);
It's important to note that PHP is case-sensitive when it comes to variable names and class names but not for
function names. Therefore, you must use the correct letter casing when referencing variables and class
[Link], meaningful and descriptive names should be used for all identifiers to improve code
readability and maintainability. Using consistent naming conventions, such as camelCase for variables and
functions and StudlyCase for classes, can make your code more organized and easier to understand.
➢ Keywords :
Keywords in PHP are reserved words that have special meanings and purposes within the PHP language. These
words cannot be used as identifiers (e.g., variable names, function names, class names) because they are
6

predefined and serve specific roles in the language. Here is a list of some of the most common keywords in
PHP :
1. Basic Keywords:
Echo : Used to output data to the browser. print : Similar to echo, used to output data. return: Used
to return a value from a function. include: Used to include and evaluate a specified file. require:
Used to include and evaluate a specified file, and it's considered fatal if the file is not found.
include_once: Similar to include, but ensures the file is included only once. require_once: Similar
to require, but ensures the file is included only once.
2. Control Structures:
if: Used to conditionally execute code. else: Used in conjunction with if to
execute code when the condition is false. elseif or else if: Used to add additional
conditions in an if statement. while: Used to create a loop that executes code
while a condition is true. for: Used to create a loop with a specific initialization,
condition, and increment. foreach: Used to loop through arrays and objects.
switch: Used to create a switch statement for multiple condition checks. case:
Used within a switch statement to specify different cases. break: Used to exit a
loop or a switch statement.
continue: Used to skip the current iteration of a loop.
3. Data Types:
int, integer: Used to represent integer data types. float, double:
Used to represent floating-point (decimal) data types. string: Used
to represent string data types. bool, boolean: Used to represent
Boolean data types. array: Used to represent arrays. object: Used
to represent objects.
null: Used to represent the absence of a value.
4. Classes and Objects:
class: Used to define a class. new: Used to create an instance of a class. this: Used to refer to
the current object within a class. public, private, protected: Used to specify the visibility of class
members (properties and methods).
static: Used to define static methods and properties within a class.
5. Error Handling:
try: Marks the beginning of a block of code to be tested for
exceptions. catch: Handles exceptions that are thrown within a try
block. throw: Throws an exception within a block of code.
finally: Marks a block of code that is always executed, whether an exception is thrown or not.
6. Namespaces:
namespace: Used to declare a namespace.
use: Used to import classes or functions from a namespace.
7. Other Keywords:
global: Used to access a global variable from within a
function. const: Used to define class constants. define: Used
to define global constants.
include_once, require_once: Used to include files only once.
7

These are some of the most commonly used keywords in PHP. It's important to understand their meanings and
how they are used in PHP programming to write effective and efficient code.
➢ Data Types :
PHP provides eight types of values, or data types. Four are scalar (single-value) types: integers, floating-point
numbers, strings, and Booleans. Two are compound (collection) types: arrays and objects. The remaining two
are special types: resource and NULL.
In PHP, single value data types or scalar data types represent individual values, as opposed to compound data
types like arrays or objects. PHP has several scalar data types, each of which can hold a single value. Here are
the main scalar data types in PHP :
1. Integer (int):
The integer data type represents whole numbers, both positive and negative, without a fractional or decimal
component. Examples of integers include -42, 0, and 100.
$age = 30; // an integer variable
2. Floating-Point (float or double):
Floating-point data types represent numbers with a decimal point or in scientific notation. Examples
include 3.14159, -0.01, and 2.5e3.
$pi = 3.14159; // a floating-point variable
3. String:
The string data type represents sequences of characters, such as text. Strings can be enclosed in single
quotes (') or double quotes (").
$name = "John"; // a string variable
4. Boolean (bool):
Boolean data types represent one of two possible values: true or false. Booleans are often used for
conditional statements and comparisons.
$isMember = true; // a boolean variable

In PHP, arrays and objects are compound data types used to store collections of values. They are not scalar
data types because they can hold multiple values, including other data types. Here's an overview of arrays and
objects in PHP :
1. Arrays:
Arrays are ordered collections of values that can be of various data types, including scalars, other arrays,
and objects. They are versatile and commonly used for storing and manipulating multiple pieces of data. In
PHP, there are three main types of arrays:
Indexed Arrays: These use numeric indices (0, 1, 2, etc.) to access elements.
Associative Arrays: These use named keys to access elements (key-value pairs).
Multidimensional Arrays: These are arrays of arrays, allowing you to create complex data structures.
Example of an indexed array :
$fruits = ['apple', 'banana', 'cherry'];
Example of an associative array:
$person = ['first_name' => 'John', 'last_name' => 'Doe', 'age' => 30]; Example
of a multidimensional array :
$matrix = [
[1, 2, 3],
[4, 5, 6],
8

[7, 8, 9]];
2. Objects:
Objects are instances of classes and are used to model complex, structured data. They can contain properties
(variables) and methods (functions). Objects are integral to object-oriented programming (OOP) in PHP.
9

To create an object, you define a class and then instantiate it using the new keyword. You can access object
properties and methods using the arrow operator (->).
Example of defining a class and creating an object:
class Person { public $name; public
function sayHello() { echo "Hello, my
name is " . $this->name;
}
}
$person = new Person();
$person->name = "John";
Example of accessing an object's property and calling a method :
$person->sayHello();
// Output: Hello, my name is John
1. Resource:
The resource data type represents a special type of variable that holds a reference to an external resource,
such as a database connection, file handle, or socket. Resources are typically created and manipulated by
various PHP extensions or functions that interact with external systems.
Resources are not typically used for general data storage but are important for managing external resources
and connections.
For example, when working with a database, you might obtain a resource representing the database connection.
Example of working with a resource (database connection):
$db = mysqli_connect("localhost", "username", "password", "database"); //
$db is a resource representing the database connection
2. NULL :
The NULL data type represents the absence of a value. It is often used to indicate that a variable has not
been assigned a value or that a variable should be reset to an undefined state.
It's important to note that NULL is not the same as an empty string, zero, or false. It is a distinct data type
in PHP.
Example of using NULL:$variable = null; // Assigning a variable the value of NULL
Example of checking for NULL:
if ($variable === null) { echo
"The variable is NULL.";
}
These two special data types, resource and NULL, serve unique purposes in PHP. resource is used to manage
external resources, while NULL is used to indicate the absence of a value. Understanding them roles and when
to use them is essential in PHP programming.
➢ Variables :
In PHP, variables are used to store and manipulate data. They have various characteristics, including variable
variables, variable references, and variable scope. Let's explore these concepts:
1. Variables in PHP:
Variables are used to store data, such as numbers, strings, and objects.
Variable names must start with a dollar sign ($) followed by a letter or underscore, and can contain letters,
numbers, and underscores. Variable names are case-sensitive in PHP.
Example:
$name = "John";
// A variable storing a string
10

$age = 30;
// A variable storing an integer
2. Variable Variables:
PHP allows you to use a variable's value as the name of another variable. This is called "variable variables."
You use a double dollar sign ($$) to indicate a variable variable.
Example:
$variableName = "age";
$$variableName = 25; // Creates a variable $age with a value of 25
3. Variable References:
PHP supports variable references, which allow multiple variables to refer to the same data in memory.
This is useful when you want to manipulate the same value in different parts of your code. You
use the ampersand (&) symbol to create a reference.
Example:
$original = 10;
$reference = &$original;
// $reference and $original now refer to the same data
$reference = 20;
// Changes both $reference and $original to 20
4. Variable Scope:
Variable scope defines where a variable can be accessed within your code. PHP has three main types of
variable scope:

Local Variables:
Local variables are declared inside a function or method and are only accessible within that function. They
do not exist outside the function's scope.
Example:
function myFunction() {
$localVariable = "Local variable"; }

Global Variables:
Global variables are declared outside of any function and can be accessed from anywhere in the script. You
need to use the global keyword inside a function to modify a global variable.
Example:
$globalVariable = "Global variable";
function myFunction() { global
$globalVariable;
$globalVariable = "Modified global variable"; }

Static Variables:
Static variables are local variables that retain their values between function calls. They are initialized only
once when the function is first called.
Example:
function countCalls() { static
$count = 0;
$count++;
11

echo "Function has been called $count times.<br>";


}
These concepts are fundamental to working with variables in PHP. Understanding variable scope, variable
references, and variable variables allows you to write more flexible and efficient code.
➢ Expressions and Operators:
In PHP, an expression is a combination of one or more values, variables, operators, and functions that can
be evaluated to produce a single value. Expressions are used in PHP to perform operations, make
decisions, and manipulate data.
Operators in PHP are symbols or keywords used to perform specific operations on one or more values or
variables. PHP supports a wide range of operators, including arithmetic, comparison, logical, and assignment
operators, among others.
Number of Operands:
The number of operands refers to how many values an operator operates on. In PHP, operators can be
categorized into unary (1 operand), binary (2 operands), and ternary (3 operands) operators.
Unary operators work with a single operand. For example, the - operator in -5 is a unary operator.
Binary operators work with two operands. For example, the + operator in 2 + 3 is a binary operator.
Ternary operators, like the conditional (ternary) operator ? :, work with three operands.
For example, $a > $b ? "True" : "False" uses the ternary operator.
Operator Precedence:
Operator precedence defines the order in which operators are evaluated when an expression contains
multiple operators. Operators with higher precedence are evaluated before those with lower precedence.
PHP follows a specific order of precedence for operators. For example, multiplication (*) has higher
precedence than addition (+), so in 2 + 3 * 4, 3 * 4 is evaluated first, and the result is added to 2.
You can use parentheses () to override the default precedence and specify the order of evaluation.
Expressions within parentheses are always evaluated first.
Operator Associativity:
Operator associativity determines the order in which operators of the same precedence are evaluated when
they appear in sequence without parentheses.
PHP operators typically have left-to-right associativity, which means they are evaluated from left to right.
For example, in 2 + 3 + 4, the leftmost + is evaluated first, and then the rightmost + is evaluated.
Some operators, like the assignment operator =, have right-to-left associativity, meaning they are evaluated
from right to left. For example, in $a = $b = $c, $b = $c is evaluated first.
Implicit Casting :
Implicit casting, also known as type juggling, refers to the automatic conversion of one data type to another
by the PHP interpreter to perform operations.
PHP performs implicit casting when necessary to ensure that operators work with compatible data types.
For example, when you add an integer and a float, PHP implicitly converts the integer to a float before
performing the addition.
Implicit casting can sometimes lead to unexpected results, so it's essential to be aware of the data types you
are working with in your code.
• You can also use explicit type casting to convert values when needed.
1. Arithmetic Operator :
Arithmetic operators in PHP are used to perform mathematical calculations on numeric values. These
operators allow you to perform basic arithmetic operations, such as addition, subtraction,
multiplication, division, and more. Here are the common arithmetic operators in PHP:
1. Addition (+):
12

Used to add two or more numeric values.


Example:
$sum = 5 + 3;
// $sum is 8
2. Subtraction (-):

Used to subtract one numeric value from another.

Example:
$difference = 10 - 4;
// $difference is 6
3. Multiplication (*):

Used to multiply two or more numeric values.

Example:
$product = 6 * 7;
// $product is 42
4. Division (/):

Used to divide one numeric value by another.

Example:
$quotient = 18 / 3;
// $quotient is 6
5. Modulus (%):

Returns the remainder of the division of one numeric value by another.

Example:
$remainder = 10 % 3;
// $remainder is 1 (10 divided by 3 leaves a remainder of 1)
6. Exponentiation ()**:
Raises one numeric value to the power of another. Example:
$result = 2 ** 3;
// $result is 8 (2 raised to the power of 3)
These arithmetic operators are used extensively in PHP for performing various mathematical calculations,
including basic arithmetic, power calculations, and finding remainders. You can combine these operators to
create complex expressions for more advanced calculations.
2. Strings Concatenation Operator :
The string concatenation operator in PHP is a period (.) that is used to combine or concatenate two or more
strings together. This operator allows you to join multiple strings to create a single, longer string. Here's
how it works:
$string1 = "Hello, ";
$string2 = "world!";
13

$combinedString = $string1 . $string2;


In this example, the . operator is used to concatenate the contents of $string1 and $string2, resulting in the
$combinedString variable containing the string "Hello, world!".
You can use the concatenation operator to join not only string literals but also variables, function return values,
and any expressions that produce strings.
For example:
$name = "Alice";
$greeting = "Hello, " . $name . "!";
You can also use the concatenation operator within echo or print statements to output concatenated strings:
echo "Today is " . date("Y-m-d") . ". Happy coding!";
The string concatenation operator is a fundamental tool for working with text and building dynamic strings
in PHP. It allows you to create more complex and customized output by combining different pieces of text
as needed.
3. Auto Increment and Auto Decrement Operator :
In PHP, the auto-increment and auto-decrement operators are used to increment or decrement the value
of a variable by 1. These operators are convenient for performing operations where you need to
increase or decrease a variable's value by a fixed amount. The auto-increment operator and the auto
decrement operator have both pre-increment and post-increment forms, as well as pre-decrement and
post-decrement forms.
Here's a breakdown of these operators:
1. Pre-increment (++$variable) and Pre-decrement (--$variable):
The pre-increment operator increases the value of a variable by 1 and then returns the updated value.
The pre-decrement operator decreases the value of a variable by 1 and then returns the updated value.
$a = 5;
$b = ++$a;
// Pre-increment: $b is 6, $a is 6
$c = --$b;
// Pre-decrement: $c is 5, $b is 5
2. Post-increment ($variable++) and Post-decrement ($variable--):
The post-increment operator returns the current value of a variable and then increases the value by
1.
The post-decrement operator returns the current value of a variable and then decreases the value
by 1. $x = 10;
$y = $x++;
// Post-increment: $y is 10, $x is 11
$z = $y--;
// Post-decrement: $z is 10, $y is 9
The choice between pre-increment/decrement and post-increment/decrement depends on whether you want to
use the value before or after the operation. Pre-increment and pre-decrement change the variable's value and
return the updated value, while post-increment and post-decrement return the current value before changing it.
Auto-increment and auto-decrement operators are commonly used for loop counters, index manipulation, and
other scenarios where you need to adjust the value of a variable as part of a computation.
4. Comparison Operator:
Comparison operators in PHP are used to compare two values or expressions and return a Boolean result (true
or false) based on the comparison. These operators are essential for making decisions and conditional
statements. Here are the common comparison operators in PHP:
14

1. Equal (==) Operator:


Checks if two values are equal, regardless of their data types. Example:
$a == $b
2. Not Equal (!=) Operator:
Checks if two values are not equal, regardless of their data types. Example:
$a != $b
3. Identical (===) Operator:
Checks if two values are equal and of the same data type. Example:
$a === $b
4. Not Identical (!==) Operator:
Checks if two values are not equal or not of the same data type. Example:
$a !== $b
5. Greater Than (>) Operator:
Checks if the left operand is greater than the right operand. Example: $a > $b
6. Less Than (<) Operator:
Checks if the left operand is less than the right operand. Example:
$a < $b
7. Greater Than or Equal To (>=) Operator:
Checks if the left operand is greater than or equal to the right operand. Example:
$a >= $b
8. Less Than or Equal To (<=) Operator:
Checks if the left operand is less than or equal to the right operand. Example:
$a <= $b
9. Spaceship (<=>) Operator (PHP 7.0 and later):
Compares two values and returns:
1 if the left operand is greater
0 if they are equal
1 if the right operand is greater Example: $result = $a <=> $b
10. Null Coalescing (??) Operator (PHP 7.0 and later):
Returns the left operand if it is not null, otherwise, it returns the right operand. Example:
$result = $a ?? $b
These comparison operators are used in conditional statements, such as if, while, and switch, to control the
flow of a PHP program by evaluating conditions and making decisions based on the results of these
comparisons. They are fundamental for building logic and control structures in PHP.
5. Bitwise Operator:
Bitwise operators in PHP are used to manipulate the individual bits of integers. These operators are helpful
for low-level programming tasks, such as working with binary data, encoding/decoding flags, and performing
bit-level operations. Here are the bitwise operators available in PHP:
1. Bitwise AND (&) Operator:
Performs a bitwise AND operation on each pair of corresponding bits of two integers. Sets
each bit to 1 if both corresponding bits are 1.
Example: $result = $a & $b
2. Bitwise OR (|) Operator:
Performs a bitwise OR operation on each pair of corresponding bits of two
integers. Sets each bit to 1 if at least one of the corresponding bits is 1. Example:
$result = $a | $b
15

3. Bitwise XOR (^) Operator:


Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits of two
integers. Sets each bit to 1 if the corresponding bits are different (one 0 and one 1). Example:
$result = $a ^ $b
4. Bitwise NOT (~) Operator:
Performs a bitwise NOT operation, which inverts each bit of an integer.
Sets 0 bits to 1 and 1 bits to 0.
Example: $result = ~$a5. Left Shift (<<) Operator:
Shifts the bits of an integer to the left by a specified number of positions.
Fills the vacant positions with zeros.
Example: $result = $a << 2
6. Right Shift (>>) Operator:
Shifts the bits of an integer to the right by a specified number of positions.
For signed integers, it fills the vacant positions with the sign bit (arithmetic shift).
For unsigned integers, it fills the vacant positions with zeros (logical shift).
Example: $result = $a >> 2

7. Logical Operator :
Logical operators in PHP are used to combine or modify the logical values (true or false) of expressions or
conditions. These operators are fundamental for controlling the flow of a program by evaluating conditions
and making decisions based on the results of these logical evaluations. PHP provides the following logical
operators:
1. Logical AND (&& and and) Operator:
The logical AND operator returns true if both expressions on its left and right sides are true. Otherwise, it
returns false. Example:
$a = true;
$b = false;
$result = $a && $b; // $result is false
2. Logical OR (|| and or) Operator:
The logical OR operator returns true if at least one of the expressions on its left or right side is true. It returns
false only if both expressions are false.
Example:
$a = true;
$b = false;
$result = $a || $b; // $result is true
3. Logical NOT (! and not) Operator:
The logical NOT operator is a unary operator that negates the logical value of an expression. If the
expression is true, it returns false; if the expression is false, it returns true. Example:
$a = true;
$result = !$a; // $result is false4.
4. Logical XOR (xor ) Operator:
The logical XOR (exclusive OR) operator returns true if exactly one of the expressions on its left or right
side is true. It returns false if both expressions are true or both are false.
Example:
$a = true;
$b = false;
16

$result = $a xor $b; // $result is true


Logical operators are commonly used in conditional statements (e.g., if, while, for) to control the flow
of a PHP program based on logical conditions.
8. Casting Operator :
Casting operators (also known as type casting or type conversion operators) are used to explicitly change the
data type of a value or variable from one type to another. PHP provides several casting operators, each
designed to convert values to specific data types :
1. (int) or (integer):
The (int) casting operator is used to explicitly convert a value to an integer. It truncates decimal portions if
the value is a float.
Example:
$floatValue = 3.14;
$intValue = (int)$floatValue; // $intValue is 3
2. (float) or (double) or (real):
The (float) casting operator is used to explicitly convert a value to a floating-point number (float).
Example:
$intValue = 42;
$floatValue = (float)$intValue; // $floatValue is 42.0
3. (string):
The (string) casting operator is used to explicitly convert a value to a string.
Example:
$number = 123;
$stringNumber = (string)$number; // $stringNumber is "123"
4. (bool) or (boolean):
The (bool) casting operator is used to explicitly convert a value to a boolean (true or false).
Example:$intValue = 0;
$boolValue = (bool)$intValue; // $boolValue is false
5. (array):
The (array) casting operator is used to explicitly convert a value to an array. Example:
$string = "Hello, World";
$arrayFromString = (array)$string; // $arrayFromString is an array with each character as an element
6. (object):
The (object) casting operator is used to explicitly convert a value to an object.
Example:
$array = [1, 2, 3];
$objectFromArray = (object)$array; // $objectFromArray is an object with array elements accessible as
properties
7. (unset):
The (unset) casting operator is used to unset (clear) a variable.
Example:
$value = "Hello";
$unsetValue = (unset)$value; // $value is unset (null)
Casting operators are handy when you need to ensure that a value is treated as a specific data type.
9. Assignment Operator :
17

In PHP, assignment operators are used to assign values to variables. These operators allow you to store data
in variables for later use. PHP provides a variety of assignment operators for different scenarios. Here are
some of the common assignment operators:
1. Assignment Operator (=):
The basic assignment operator is used to assign a value to a variable.
Example:
$x = 5; // $x now contains the value 5
2. Addition Assignment Operator (+=):
Adds a value to the variable and assigns the result to the variable. Example:
$y = 10;
$y += 3; // $y is now 13 (10 + 3)
3. Subtraction Assignment Operator (-=):
Subtracts a value from the variable and assigns the result to the variable. Example:$z
= 15;
$z -= 7; // $z is now 8 (15 - 7)
4. Multiplication Assignment Operator (*=):
Multiplies the variable by a value and assigns the result to the variable. Example:
$w = 4;
$w *= 6; // $w is now 24 (4 * 6)
5. Division Assignment Operator (/=):
Divides the variable by a value and assigns the result to the variable. Example:
$v = 20;
$v /= 5; // $v is now 4 (20 / 5)
6. Modulus Assignment Operator (%=):
Performs the modulus operation on the variable and assigns the result to the variable. Example:
$u = 12;
$u %= 5; // $u is now 2 (12 % 5)
7. Concatenation Assignment Operator (.=):
Concatenates a string to the variable's existing value and assigns the result to the variable. Example:
$text = "Hello";
$text .= ", World!"; // $text is now "Hello, World!"
These assignment operators are used extensively in PHP to manipulate variables by performing operations and
storing results.
10. Assignment Operator :
In PHP, there are several miscellaneous operators that serve various purposes beyond arithmetic, comparison,
and assignment operations. These operators are used in specific situations and can be quite handy in certain
scenarios. Here are some of the miscellaneous operators in PHP:
1. Ternary Conditional Operator (? :):
The ternary operator is a shorthand way of expressing conditional statements. It allows you to return one
of two values depending on the result of a condition.
Syntax: $condition ? $value_if_true : $value_if_false
Example:
$age = 25;
$message = ($age >= 18) ? "You are an adult" : "You are a minor";
2. Null Coalescing Operator (??) (PHP 7.0 and later):
18

The null coalescing operator is used to provide a default value for a variable or expression when the original
value is null.
Syntax: $value ?? $default_value
Example:
$username = $_GET['user'] ?? "Guest";
3. Error Control Operator (@):
The error control operator suppresses error messages generated by PHP. It's used to prevent error messages
from being displayed to the user.
Example:
$result = @file_get_contents('[Link]');
4. Execution Operator (backticks or shell_exec):
The execution operator allows you to run shell commands and capture the output of those commands in a
PHP variable.
Example:
$output = `ls -l`;
5. Concatenation Operator (.):
As mentioned earlier, the concatenation operator is used to join two or more strings together. Example:
$str1 = "Hello, ";
$str2 = "world!";
$combinedString = $str1 . $str2;
6. Instanceof Operator:
The instanceof operator is used to check if an object is an instance of a particular class.
Example:
if ($object instanceof MyClass) {
// Do something if $object is an instance of MyClass }
7. Type Operators (is_array, is_string, is_numeric, etc.):
PHP provides a set of type operators that can be used to check the type of a variable or value.
Example:
if (is_array($variable)) {
// Check if $variable is an array
}
These miscellaneous operators extend the functionality of PHP and help you accomplish specific tasks or
handle edge cases in your code. It's important to use themeffectively and consider their implications when
designing your applications.

UNIT II
Controlling Program Flow: Writing Simple Conditional Statements - Writing More ComplexConditional
Statements – Repeating Action with Loops – Working with String and NumericFunctions ➢ Flow Control
Statements :
Flow control statements in PHP are used to determine the order in which a program's instructions are executed.
They allow you to create decision-making structures, loops, exception handling, and more. Below are
examples of various flow control statements in PHP, including their syntax and usage.
1. if Statement:
The if statement is used for conditional execution. It runs a block of code if a specified condition is true.
19

Syntax :
if (condition) {
// Code to execute when the condition is true
} elseif (another_condition) {
// Code to execute when another condition is true
} else {
// Code to execute when none of the conditions are true }
Example : $score
= 85; if ($score >=
90) { echo "A
grade";
} elseif ($score >= 80) { echo
"B grade";
} else { echo "C
grade";
}
2. switch Statement:
The switch statement is used to select one of many code blocks to be executed.
Example:
Syntax :
switch (expression) { case
value1:
// Code to execute when expression equals
value1 break; case value2:
// Code to execute when expression equals value2 break;
// Additional cases... default:
// Code to execute when no case matches}
Example : $day =
"Monday"; switch
($day) { case
"Monday":
echo "It's the start of the week.";
break; case "Friday": echo
"TGIF!"; break; default:
echo "Enjoy your day.";
}
3. while Loop:
The while loop repeatedly executes a block of code as long as a specified condition is true.
Syntax :
while (condition) {
// Code to execute as long as the condition is true }
Example : $count = 1;
while ($count <= 5) { echo
"Count: $count<br>";
$count++;
}
20

4. for Loop:
The for loop is used to iterate a specific number of times.
Syntax :
for (initialization; condition; increment) {
// Code to execute as long as the condition is true }
Example:
for ($i = 1; $i <= 5; $i++) {
echo "Iteration $i<br>";
}5. foreach Loop:
The foreach loop is used to iterate over elements in an array or other iterable objects.
Syntax :
foreach ($array as $value) {
// Code to execute for each element in the array }
Example :
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) { echo "I like
$fruit<br>";
}

Functions :

PHP Functions

A function is a block of code that performs a specific task and can be reused multiple times.

1. Predefined (Built-in) Functions

PHP provides many built-in functions that are ready to use.

🔸 Examples of Predefined Functions:


✅ String Functions:
Function Description Example

strlen() Returns length of string strlen("Hello") → 5 strrev()

Reverses a string strrev("PHP") → "PHP"

strtoupper() Converts to uppercase strtoupper("php") → "PHP"

✅ Math Functions:
Function Description Example

abs() Absolute value abs(-7) → 7 sqrt()

Square root sqrt(16) → 4


21

round() Rounds number round(4.6) → 5

✅ Date/Time Functions:
Function Description Example

date() Returns current date/time date("Y-m-d") → 2025-06-22

✅ Array Functions:

Function Description Example

count() Counts elements in array count([1,2,3]) → 3

array_sum() Sum of array values array_sum([10,20]) → 30

UNIT III
Working with Arrays: Storing Data in Arrays – Processing Arrays with Loops and Iterations –Using Arrays
with Forms - Working with Array Functions – Working with Dates and Times.
Arrays:

Arrays are one of the most important data structures in PHP. They allow you to store multiple values in a single
variable. PHP arrays can hold values of different types, such as strings, numbers, or even other arrays.
Understanding how to use arrays in PHP is important for working with data efficiently.
• PHP offers many built-in array functions for sorting, merging, searching, and more.
• PHP Arrays can store values of different types (e.g., strings, integers, objects, or even other arrays) in the
same array.
• They are dynamically sized.
• They allow you to store multiple values in a single variable, making it easier to manage related data.
Types of Arrays in PHP
There are three main types of arrays in PHP:
1. Indexed Arrays
Indexed arrays use numeric indexes starting from 0. These arrays are ideal when you need to store a list of
items where the order matters.
<?php
$fruits = array("apple", "banana", "cherry");
echo $fruits[0]; // Outputs: apple
?>

Output
22

apple
2. Associative Arrays
Associative arrays use named keys, which are useful when you want to store data with meaningful identifiers
instead of numeric indexes.
<?php
$person = array("name" => "GFG", "age" => 30, "city" => "New York"); echo
$person["name"];
?>

Output

GFG
3. Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays as elements. These are used to represent more
complex data structures, such as matrices or tables.
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"GFG" => array("age" => 22, "grade" => "B")
);
echo $students["GFG"]["age"];
?>

Output

22
Creating Array in PHP
In PHP, arrays can be created using two main methods:
1. Using the array() function
The traditional way of creating an array is using the array() function.
$fruits = array("apple", "banana", "cherry");
2. Using short array syntax ([])
In PHP 5.4 and later, you can use the shorthand [] syntax to create arrays.
$fruits = ["apple", "banana", "cherry"];
You can also create associative arrays by specifying custom keys:
$person = ["name" => "GFG", "age" => 30];
Accessing and Modifying Array Elements
1. Accessing Array Elements
You can access individual elements in an array using their index (for indexed arrays) or key (for associative
arrays).
23

• Accessing Indexed Array:


$fruits = ["apple", "banana", "cherry"];
echo $fruits[0]; // Outputs: apple
• Accessing Associative Array:
$person = ["name" => "GFG", "age" => 30];
echo $person["name"]; // Outputs: GFG
2. Modifying Array Elements
You can modify an existing element by assigning a new value to a specific index or key.
• Modifying Indexed Array Element:

1. Adding Array Elements


You can add new elements to an array using the following methods:
• array_push(): Adds elements to the end of an indexed array.
$fruits = ["apple", "banana"]; array_push($fruits, "cherry"); // Adds "cherry" to the end
• array_unshift(): Adds elements to the beginning of an indexed array.
array_unshift($fruits, "pear"); // Adds "pear" to the beginning
• Direct assignment: Adds an element to an associative array.
$person["city"] = "New York";
2. Removing Array Elements
To remove items from an array, you can use several functions:
• array_pop(): Removes the last element from an indexed array.
array_pop($fruits);
• array_shift(): Removes the first element from an indexed array.
array_shift($fruits);
• unset(): Removes a specific element from an array by key or index.
unset($fruits[2]); // Removes the element with index 2
Array Functions
PHP provides a wide range of built-in functions to work with arrays. Here are some common array functions:
• Array Merge: The array_merge() function combines two or more arrays into one.
$array1 = [1, 2, 3];

$array2 = [4, 5, 6];

$merged = array_merge($array1, $array2);


print_r($merged); // Outputs: [1, 2, 3, 4, 5, 6]
• Array Search: The in_array() function checks if a specific value exists in an array.
$fruits = ["Apple", "Banana", "Cherry"];
if (in_array("Banana", $fruits)) {
24

echo "Banana is in the array!";


}
• Array Sort: The sort() function sorts an indexed array in ascending order.
$numbers = [3, 1, 4, 1, 5];
sort($numbers);
print_r($numbers); // Outputs: [1, 1, 3, 4, 5]

✅ Working with Array Functions

Function Description Example

count() Count elements count($colors)

array_push() Add element at end array_push($colors, "Orange")

array_pop() Remove last element array_pop($colors)

in_array() Check if value exists in_array("Red", $colors)

sort() Sort values in ascending order sort($colors)

array_merge() Combine two arrays array_merge($a1, $a2)

Array Iteration
You can loop through arrays using loops such as foreach or for.
• Using foreach Loop:
$fruits = ["Apple", as "Banana", "Cherry"];
foreach ($fruits $fruit) {
echo $fruit . "<br>";
}
• Using for Loop:
$numbers ($i = = [1, < 2, 3, $i++) 4];
for 0; $i count($numbers); {
echo $numbers[$i] . "<br>";
}

PHP Date and Time


PHP provides functions to work with dates and times, allowing developers to display the current date/time,
manipulate and format dates, and perform operations like date comparisons, time zone adjustments, and more.
Why are Date and Time Important in PHP?
In web development, date and time are important for:
• Displaying the current date and time on a website (e.g., last updated time, current date for a blog post).
• Compare and manipulate dates (e.g., calculating age from a birthdate).
25

• Store date and time information in databases.


• Handle time zone adjustments for users in different regions.
Getting the Current Date and Time
The simplest way to get the current date and time in PHP is by using the date() function. This function formats
the current local date and time based on the format string you provide.
Syntax:
date(format, timestamp);
In this syntax:
• The format parameter in the date() function specifies the format of the returned date and time.
• The timestamp is an optional parameter, if it is not included, then the current date and time will be used.
Example 1: Display Current Date
<?php echo date("Y-m-d"); // Output: 2025-
04-04 ?>

Output

2025-04-04
In this example:
• Y stands for the four-digit year.
• m represents the two-digit month.
• d represents the two-digit day.
Example 2: Display Current Date and Time
<?php echo date("Y-m-d
H:i:s");
?>
Output

2025-04-04 12:34:11
In this example:
• H represents hours in 24-hour format.
• i represents minutes.
• s represents seconds.
Date Formatting in date() function
The format parameter of the date() function is a string that can contain multiple characters, allowing to generate
the dates in various formats. Date-related formatting characters that are commonly used in the format string:
• d: Represents the day of the month, two digits with leading zeros (01 or 31).
• D: Represents the day of the week in the text as an abbreviation (Mon to Sun).
• m: Represents month in numbers with leading zeros (01 or 12).
• M: Represents month in text, abbreviated (Jan to Dec).
• y: Represents the year in two digits (08 or 14).
• Y: Represents the year in four digits (2008 or 2014).
The parts of the date can be separated by inserting other characters, like hyphens (-), dots (.), slashes (/), or
spaces to add additional visual formatting.
Example: The below example explains the usage of the date() function in PHP.
26

<?php echo "Today's date in various formats:"


. "\n"; echo date("d/m/Y") . "\n"; echo
date("d-m-Y") . "\n";
echo date("d.m.Y") . "\n";
echo date("d.M.Y/D");
?>

Output

Today's date in various formats:


04/04/2025
04-04-2025
04.04.2025
[Link].2025/Fri
PHP time() Function
The time() function is used to get the current time as a Unix timestamp (the number of seconds since the
beginning of the Unix epoch: January 1, 1970, 00:00:00 GMT).
The following characters can be used to format the time string:
• h: Represents the hour in 12-hour format with leading zeros (01 to 12).
• H: Represents the hour in 24-hour format with leading zeros (00 to 23).
• i: Represents minutes with leading zeros (00 to 59).
• s: Represents seconds with leading zeros (00 to 59).
• a: Represents lowercase antemeridian and post meridian (am or pm).
• A: Represents uppercase antemeridian and post meridian (AM or PM).
Example: The below example explains the usage of the time() function in PHP.
<?php
$timestamp = time(); echo($timestamp);
echo "\n"; echo(date("F d, Y h:i:s A",
$timestamp)); ?>

Output

1743772332
April 04, 2025 01:12:12 PM
Get Your Time Zone
In PHP, you can easily get the current time zone using the date_default_timezone_get() function. This function
returns the default time zone set in your PHP configuration or the time zone that has been explicitly set within
your script using date_default_timezone_set().
Syntax:
date_default_timezone_get();
27

<?php
date_default_timezone_set("America/New_York")
; echo "The time is " . date("h:i:sa"); ?>

Output
The time is 01:26:09pm

Working with Timestamps:

php CopyEdit echo time(); //


Unix timestamp

🔸 Convert to Date:

php
CopyEdit
echo date("Y-m-d", strtotime("next Monday"));

UNIT IV
Using Functions and Classes: Creating User-Defined Functions - Creating Classes – UsingAdvanced OOP
Concepts. Working with Files and Directories: Reading FilesWriting FilesProcessing Directories

🔹 2. User-defined Functions

A function in PHP is a self-contained block of code that performs a specific task. It can accept inputs
(parameters), execute a set of statements, and optionally return a value.
• PHP functions allow code reusability by encapsulating a block of code to perform specific tasks.
• Functions can accept parameters and return values, enabling dynamic behavior based on inputs.
• PHP supports both built-in functions and user-defined functions, enhancing flexibility and modularity in
code.
Creating a Function in PHP
A function is declared by using the function keyword, followed by the name of the function, parentheses
(possibly containing parameters), and a block of code enclosed in curly braces.
Syntax
function functionName($param1, $param2) {
// Code to be executed
return $result; // optional
}
In this syntax:
• function is a keyword that starts the function declaration.
• functionName is the name of the function.
• $param1 and $param2 are parameters (optional) that can be passed to the function.
• The return statement (optional) sends a value back to the caller.
28

Calling a Function in PHP


Once a function is declared, it can be invoked (called) by simply using the function name followed by
parentheses.
<?php function sum($a,
$b) {
return $a + $b;
} echo sum(5, 3); // Outputs:
8 ?>

Output

8
In this example:
• The function sum() is defined to take two parameters, $a and $b, and return their sum.
• The function is called with 5 and 3 as arguments, and it returns the result, which is 8.
Types of Functions in PHP PHP
has two types of functions:
1. User-Defined Functions
A user-defined function is created to perform a specific task as per the developer's need. These functions can
accept parameters, perform computations, and return results.
Now, let us understand with the help of example:
<?php function
addNumbers($a, $b) { return
$a + $b;
} echo addNumbers(5, 3); // Output:
8 ?>

Output

8
In this example:
• The function addNumbers is defined by the user to take two parameters, $a and $b, and returns their sum
($a + $b).
• The function is called with 5 and 3 as arguments, so it adds these numbers together.
2. Built-in Functions
PHP comes with many built-in functions that can be directly used in your code. For example, strlen(), substr(),
array_merge(), date() and etc are built-in PHP functions. These functions provide useful functionalities, such
as string manipulation, date handling, and array operations, without the need to write complex logic from
scratch.
<?php
$str = "Hello, World!"; echo
strlen($str); // Output: 13
?>

Output
29

13
In this example:
• A string variable $str is defined with the value "Hello, World!".
• The strlen() function is the built-in function in PHP that is used to calculate the length of the string $str.
PHP Function Parameters and Arguments
Functions can accept input values, known as parameters or arguments.
• Parameters are variables defined in the function declaration that accept values.
• Arguments are the actual values passed to the function when it is called. These values can be passed to the
function in two ways:
1. Passing by Value
When you pass a value by reference, the function works with a copy of the argument. This means the original
value remains unchanged.
<?php function add($x,
$y) { $x = $x + $y;
return $x;
}

echo add(2, 3); // Outputs: 5


?>

Output

5
In this example:
• The function add() is defined with parameters $x and $y.
• The function adds $x and $y and returns the sum.
• The function is called with values 2 and 3, and the result 5 is printed.
2. Passing by Reference
By passing an argument by reference, any changes made inside the function will affect the original variable
outside the function.
<?php function
addByRef(&$x, $y) { $x = $x
+ $y;
}
$a = 5; addByRef($a,
3); echo $a; //
Outputs: 8
?>

Output

8
In this example:
30

• The function addByRef() is defined with $x passed by reference.


• The function modifies $x directly, adding $y to it.
• After calling the function with $a = 5 and 3, the value of $a becomes 8.
Returning Values in PHP Functions
Functions in PHP can return a value using the return statement. The return value can be any data type such as
a string, integer, array, or object. If no return statement is provided, the function returns null by default.
<?php function multiply($a,
$b) {
return $a * $b;
}
$result = multiply(4, 5); // $result will be 20
echo $result; // Output: 20
?>

Output

20
In this example:
• The function multiply() is defined to return the product of $a and $b.
• The function is called with 4 and 5 as arguments.
• The result 20 is returned and printed using echo.
Anonymous Functions (Closures)
PHP supports anonymous functions, also known as closures. These functions do not have a name and are often
used for passing functions as arguments to other functions.
<?php
$greet = function($name) { echo
"Hello, " . $name . "!";
};
$greet("GFG");
?>

Output

Hello, GFG!
In this example:
• An anonymous function is defined and assigned to the variable $greet.
• The function takes $name as a parameter and prints a greeting message.
• The function is called with the argument "GFG", and the greeting "Hello, GFG" is printed.
Recursion in PHP
Recursion is a process in which a function calls itself. It is often used in situations where a task can be broken
down into smaller, similar tasks.
<?php function
factorial($n) { if ($n
== 0) { return 1;
31

} else { return $n *
factorial($n - 1); } } echo
factorial(5);
?>
Output

120
In this example:
• The function factorial() is defined to calculate the factorial of a number $n using recursion.
• If $n is 0, the function returns 1 (base case); otherwise, it calls itself with $n - 1.
• When factorial(5) is called, the function recursively multiplies 5 * 4 * 3 * 2 * 1, returning 120.
Common PHP Functions
Here are some common PHP functions you should know:
1. String Functions
• strlen(): Returns the length of a string.
• strtoupper(): Converts a string to uppercase.
• strtolower(): Converts a string to lowercase.
• substr(): Returns a part of a string.
2. Array Functions
• array_push(): Adds elements to the end of an array.
• array_pop(): Removes the last element of an array.
• array_merge(): Merges two or more arrays.
3. Date and Time Functions
• date(): Returns the current date or time.
• strtotime(): Converts a string into a Unix timestamp.
• time(): Returns the current Unix timestamp.
[III ] Variable Scope:
In PHP, variables used inside functions have different scopes, which determine where and how those variables
can be accessed. There are primarily two types of variable scopes in PHP functions: local and global.
1. Local Scope (Function Scope):
• Variables defined within a function are said to have local scope.
• Local variables are only accessible within the function in which they are defined.
• They are not accessible outside of the function.
Example of local scope :
function myFunction() {
$localVariable = "I am local!";
echo $localVariable;
}
myFunction();
// Output: I am local!
echo $localVariable; // This will result in an error because $localVariable is not defined in the global scope.
2. Global Scope:
• Variables defined outside of all functions are said to have global scope.
• Global variables can be accessed from anywhere in the script, including inside functions.
32

• To access a global variable within a function, We need to use the global keyword or the
$GLOBALS superglobal. Example of global scope with global keyword :
$globalVariable = "I am global!"; function
myFunction() { global $globalVariable; // Access the
global variable echo $globalVariable; }

A class defines the structure of an object. It contains properties (variables) and methods (functions). These
properties and methods define the behavior and characteristics of an object created from the class.
Syntax:

<?php
class Camera {
// code goes here...
}
?>
<?php
class GeeksforGeeks
{ // Constructor public function construct(){ echo
'The class "' . CLASS . '" was initiated!';
}
}
// Create a new object
$obj = new GeeksforGeeks;
?>
Output
The class "GeeksforGeeks" was initiated!
In this example:
• The code defines a Car class with two properties: color and model.
• The construct method initializes the properties when a new Car object is created.
• The displayDetails method prints the car's model and color.
• A new Car object is created using new Car("Red", "Toyota"), passing values for color and model.
• The displayDetails method is called on the $myCar object to display the car's details.
Creating Objects from Classes
Once a class is defined, you can create objects based on it. Here's how you can create an object from a class:
$object = new ClassName('Hello', 'World');
echo $object->method1(); // Outputs: Hello World
In this example:
• new ClassName() creates an instance (object) of the class ClassName.
• The constructor is called with the parameters 'Hello' and 'World', which are passed to initialize the object's
properties.
• The method method1 is called on the object to display the concatenated properties.
A class defines the structure of an object. It contains properties (variables) and methods (functions). These
properties and methods define the behavior and characteristics of an object created from the class.
33

Syntax:
<?php
class Camera {
// code goes here...
}
?>
<?php
class GeeksforGeeks
{
// Constructor public function construct(){ echo
'The class "' . CLASS . '" was initiated!'; }
}
// Create a new object
$obj = new GeeksforGeeks;
?>
Output
The class "GeeksforGeeks" was initiated!
PHP File Handling
In PHP, File handling is the process of interacting with files on the server, such as reading files, writing to a
file, creating new files, or deleting existing ones. File handling is essential for applications that require the
storage and retrieval of data, such as logging systems, user-generated content, or file uploads.
Types of File Operations in PHP
Several types of file operations can be performed in PHP:
• Reading Files: PHP allows you to read data from files either entirely or line by line.
• Writing to Files: You can write data to a file, either overwriting existing content or appending to the end.
• File Metadata: PHP allows you to gather information about files, such as their size, type, and last modified
time.
• File Uploading: PHP can handle file uploads via forms, enabling users to submit files to the server.
Common File Handling Functions in PHP
• fopen() - Opens a file
• fclose() - Closes a file
• fread() - Reads data from a file
• fwrite() - Writes data to a file
• file_exists() - Checks if a file exists
• unlink() - Deletes a file
Opening and Closing Files
Before you can read or write to a file, you need to open it using the fopen() function, which returns a file
pointer resource. Once you're done working with the file, you should close it using fclose() to free up resources.
34

<?php

// Open the file in read mode


$file = fopen("[Link]", "r");

if ($file) { echo "File opened


successfully!"; fclose($file); //
Close the file
} else { echo "Failed to open the
file.";
}
?>
File Modes in PHP
Files can be opened in any of the following modes:
• "w" – Opens a file for writing only. If the file does not exist, then a new file is created, and if the file
already exists, then the file will be truncated (the contents of the file are erased).
• "r" – File is open for reading only.
• "a" – File is open for writing only. The file pointer points to the end of the file. Existing data in the file is
preserved.
• "w+" – Opens file for reading and writing both. If the file does not exist, then a new file is created, and if
the file already exists, then the contents of the file are erased.
• "r+" – File is open for reading and writing both.
• "a+" – File is open for write/read. The file pointer points to the end of the file. Existing data in the file is
preserved. If the file is not there, then a new file is created.
• "x" – New file is created for write only.
Reading from Files
There are two ways to read the contents of a file in PHP. These are -
1. Reading the Entire File
You can read the entire content of a file using the fread() function or the file_get_contents() function.
<?php
$file = fopen("[Link]", "r");
$content = fread($file, filesize("[Link]")); echo $content; fclose($file);
?>
2. Reading a File Line by Line
You can use the fgets() function to read a file line by line.
<?php
$file = fopen("[Link]", "r"); if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
}
?>

Writing to Files
35

You can write to files using the fwrite() function. It writes data to an open file in the specified mode.
<?php
// Open the file in write
mode $file = fopen("[Link]",
'w'); if ($file) {
$text = "Hello world\n";
fwrite($file, $text);
fclose($file);
}?>
Deleting Files
Use the unlink() function to delete the file in PHP.
<?php

if (file_exists("[Link]")) { unlink("[Link]"); echo "File deleted successfully!";


} else {

echo "File does not exist.";


}
?>

UNIT V
Working with Database and SQL : Introducing Database and SQL- Using MySQLAdding andmodifying Data-
Handling Errors – Using SQLite Extension and PDO Extension. IntroductionXML - Simple XML and DOM
Extension SQL:

:PHP Database connection


The collection of related data is called a database. XAMPP stands for cross-platform, Apache, MySQL, PHP,
and Perl. It is among the simple light-weight local servers for website development.
Requirements: XAMPP web server procedure:
• Start XAMPP server by starting Apache and MySQL.
• Write PHP script for connecting to XAMPP.
• Run it in the local browser.
• Database is successfully created which is based on the PHP code.
In PHP, we can connect to the database using XAMPP web server by using the following path.

"localhost/phpmyadmin"
Steps in Detail:
• Open XAMPP and start running Apache, MySQL and FileZilla
36

• Now open your PHP file and write your PHP code to create database and a table in your database.
PHP code to create a database:
<?php

// Server name must be localhost


$servername = "localhost";
// In my case, user name will be root
$username = "root";
// Password is empty
$password = "";
// Creating a connection
$conn = new mysqli($servername,
$username, $password); 37
// Check connection if
($conn->connect_error) {
die("Connection failure: "
. $conn->connect_error);
}

// Creating a database named geekdata


$sql = "CREATE DATABASE geekdata";
if ($conn->query($sql) === TRUE) { echo
"Database with name geekdata";
} else { echo "Error: " . $conn-
>error;
}
// Closing connection
$conn->close();
?>
• Save the file as "[Link]" in htdocs folder under XAMPP folder.

• Then open your web browser and type localhost/[Link]

Finally the database is created and connected to PHP.


If you want to see your database, just type localhost/phpmyadmin in the web browser and the database can be
found.
38

In relational databases, and flat file databases, a table is a set of data elements using a model of vertical columns
and horizontal rows, the cell being the unit where a row and column intersect. A table has a specified number
of columns, but can have any number of rows.
To connect to an existing database, we can pass an extra variable "database name" while connecting to MySQL.
The CREATE TABLE statement is used to create a table in MySQL.
The data types that will be used are :
1. VARCHAR:Holds a variable length string that can contain letters, numbers, and special characters. The
maximum size is specified in parenthesis.
2. INT :he INTEGER data type accepts numeric values with an implied scale of zero. It stores any integer
value between -2147483648 to 2147483647.
The attributes that are used along with data types in this article are:
1. NOT NULL: Each row must contain a value for that column, null values are not allowed.
2. PRIMARY KEY: Used to uniquely identify the rows in a table. The column with PRIMARY KEY setting
is often an ID number.
Creating tables in three different versions are described below:

Creating table using MySQLi Object-oriented Procedure Syntax :


39

PDO in PHP :
There are three main options for creating to a MySQL database server.
• MySQLi procedural
• MySQLi object-oriented
• PDO (PHP Data Objects )
MySQLi procedural and MySQLi object-oriented only support MySQL database but PDO is an advanced
method along with MySQL which supports Postgres, SQLite, Oracle, and MS SQL Server.
PDO is more secure than the first two options and it is also faster in comparison with MySQLi procedural and
MySQLi object-oriented.
PDO is a database access layer that provides a fast and consistent interface for accessing and managing
databases in PHP applications. Every DBMS has a specific PDO driver that must be installed when you are
using PDO in PHP applications.
It simplifies the database operations including:
• Creating database connection
• Executing queries
• Handling errors
• Closing the database connections
When we want to connect PHP and MySQL then we need to follow 3 steps:
• Connection with the database
• Run SQL Query
• Closing the database connection Steps for connection using PDO.
Connection:
In this step, we connect with the database

$conn = new PDO($db_name,$username,$password);


When we want the connection between PHP and MySQL using PDO then we need to create an object of the
PDO class.
$db_name = "mysql:host=localhost;dbname:gfg";

Note: $db_name contains the following information.


Run SQL query: To run SQL query we can use two methods:
• query():
$sql = $conn->query("select * from students");
• prepare():
$sql = $conn->prepare("select * from students");

Note: The prepare() method is more secure than the query() method.
Close the connection:
For closing the database connection using PDO.

$conn = null;
Parameters: It contains the following parameters.
40

• dsn: It contains the information regarding connection to the database.


• user: It contains the user name.
• password: It contains the password of the database.
Return Value:
On success, it will return the PDO object. And on failure, it will return the PDOException object.
Handling error during connection:
The PDOException object will be thrown in case of any error. We can catch the exception to handle the error.
<?php
try {
$dsn = "mysql:host=localhost;dbname=gfg";
$user = "root";
$passwd = "";
$pdo = new PDO($dsn, $user, $passwd);
}
catch (PDOException $e) { echo "Error!: " .
$e->getMessage() . "<br/>"; die();
}
?>

Output:
Error : SQLSTATE[28000] [1045]
Access denied for user 'roott'@'localhost'
(using password: NO)

Example 1: Suppose we have a database "gfg" with a table "students". We want to fetch the details like
"id" and name of all the students present in the table "students".
<?php
$dsn = "mysql:host=localhost;dbname=gfg";
$user = "root";
$passwd = "";

$pdo = new PDO($dsn, $user, $passwd);

$stm = $pdo->query("SELECT * FROM students");


$rows = $stm->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row) { printf("{$row['id']}
{$row['name']}\n");
}
?>
Output:
1 Student1
2 Student2
3 Student3
41

4 Student4
Benefits of PDO:
• Usability: PDO contains helper functions to operate automatic routine operations.
• Reusability: We can access multiple databases because it offers a unified API.
• Security: It provides protection from SQL injection because it uses a prepared statement. A prepared
statement separates the instruction of the SQL statement from the data.
• Error handling: It uses exceptions for error handling. There are three types of modes:
Silent ,Warning ,Exception
• Multiple database support: It is used to access any database which is written for the PDP driver. We need
to find a suitable driver and add them when we use them. There are several PDO drivers available like
Microsoft SQL Server, Sybase, PostgreSQL, and many more.
XML | Basics
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents
in a format that is both human-readable and machine-readable. The design goals of XML focus on simplicity,
generality, and usability across the Internet. It is a textual data format with strong support via Unicode for
different human languages. Although the design of XML focuses on documents, the language is widely used
for the representation of arbitrary data structures such as those used in web services.
1. XML stands for extensible Markup Language
2. XML is a markup language like HTML
3. XML is designed to store and transport data
4. XML is designed to be self-descriptive
Differences between XML and HTML
XML and HTML were designed with different goals:

• XML is designed to carry data emphasizing on what type of data it is. • HTML is designed to
display data emphasizing on how data looks
• XML tags are not predefined like HTML tags.
• HTML is a markup language whereas XML provides a framework for defining markup languages.
• HTML is about displaying data,hence it is static whereas XML is about carrying information,which makes
it dynamic.

DOM:
The Document Object Model (DOM) is the data representation of the objects that comprise the structure and
content of a document on the web.
The DOMDocument::createElement() function is an inbuilt function in PHP which is used to create a new
instance of class DOMElement. Syntax:
DOMElement DOMDocument::createElement( string $name, string $value )
Parameters: This function accepts two parameters as mentioned above and described below:
• $name: This parameter holds the tag name of the element.
• $value: This parameter holds the value of the element. The default value of this function creates an empty
element. The value of element can be set later using DOMElement::$nodeValue.
Return Value: This function returns a new instance of class DOMElement on success or FALSE on failure.
Below programs illustrate the DOMDocument::createElement() function in PHP: Program 1: <?php

// Create a new DOMDocument


42

$domDocument = new DOMDocument('1.0', 'iso-8859-1');

// Use createElement() function to add a new element node


$domElement = $domDocument->createElement('organization', 'GeeksforGeeks');

// Append element to the document


$domDocument->appendChild($domElement);
// Save XML file and display it echo
$domDocument->saveXML();

?>
Output:
<?xml version="1.0" encoding="iso-8859-1"?>
<organization>GeeksforGeeks</organization>

You might also like