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

Php - (Unit - i) Notes

Uploaded by

Akshada Pande
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)
10 views

Php - (Unit - i) Notes

Uploaded by

Akshada Pande
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/ 32

Unit - I

➢ 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. This unit ends by showing you PHP in action, with a quick walkthrough
of several PHP programs that illustrate common tasks, such as processing form data, interacting with a
database, and creating graphics.

• 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. This allows
for dynamic content generation, user authentication, and other server-side functionalities.

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. Command-line PHP scripts are typically run in a terminal or command prompt and can
be scheduled as cron jobs (on Unix-based systems) or as tasks in Windows Task Scheduler.

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.

It's important to note that PHP's primary strength lies in server-side web development, but it can be
a part of a broader technology stack that includes front-end technologies for creating rich client-side
applications. Other languages and frameworks are typically more commonly used for standalone desktop
or mobile GUI applications.

➢ 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.

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 groundbreaking 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 php.ini. 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. This isin contrast to
many other dynamic web page solutions, which are scripts that generate HTML. The web server processes
the PHP commands and sends their output (and any HTML from the file) to the browser. Example 1-1
shows a complete PHP page.

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 results
appear in Figure 1-2.

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:

1. Download PHP:
• Visit the PHP official website (https://windows.php.net/download/) 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 php.ini:

• Inside the PHP directory, locate the php.ini-development file and make a copy of it named
php.ini. This is the configuration file for PHP.
• Open php.ini with a text editor and configure PHP settings according to your needs. For
example, you can set the timezone, 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
(https://httpd.apache.org/download.cgi).
• Open the Apache httpd.conf 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., test.php) 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., http://localhost/test.php) 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:

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;
#########################################

It's important to note that shell-style comments are less commonly used in PHP compared to // or /*
... */ comments. Developers often use // for single-line comments and /* ... */ for multi-line comments
because they are more widely recognized and supported across different programming languages. Shell-
style comments might work in some PHP environments, but it's a good practice to use the more common
comment styles to ensure your code is readable and maintainable by a broader audience.

➢ 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

➢ 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 underscores.
• Variable 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 names.
Additionally, 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 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.

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

These scalar data types are essential building blocks for storing and manipulating single values in
PHP. You can use them to work with integers, floating-point numbers, text, and boolean values in your PHP
code.

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],
[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.
• 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

Arrays and objects provide the ability to organize and manipulate data in a structured manner, and
they are essential for more complex data-handling needs in PHP.

In PHP, there are two additional special data types: resource and NULL. These types serve specific
purposes in the language:

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 their
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


$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++;
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.
➢ Garbage Collection :
Garbage collection is a crucial aspect of memory management in programming languages like PHP.
Two common techniques used for garbage collection in PHP are reference counting and copy-on-write.
Let's explore how each of these techniques works :

1. Reference Counting:

• Reference counting is a memory management technique used in PHP to track references to


variables and objects. Each variable and object has an associated reference count.
• When a variable or object is created or assigned, its reference count is set to 1.
• When a reference to a variable or object is created (e.g., by assigning it to another variable), the
reference count is increased by 1.
• When a reference is removed (e.g., when a variable goes out of scope or is explicitly unset), the
reference count is decreased by 1.
• When the reference count of a variable or object reaches 0, it means there are no more references
to it, and it can be safely deallocated (garbage collected).
• Example:
$a = 42; // reference count for $a is 1
$b = $a; // reference count for $a and $b is 2
unset($a); // reference count for $b is 1

While reference counting is a straightforward and efficient technique for tracking references and cleaning
up memory, it has limitations. It cannot handle circular references (two objects referencing each other),
which can lead to memory leaks. PHP 7.0 and later versions introduced the "zval" (Zend value) data
structure to improve reference counting and address some of these issues.

2. Copy-on-Write (COW):

• Copy-on-write is a technique used to optimize memory usage when working with variables. Instead
of immediately duplicating the memory when a change is made to a variable, PHP employs COW to
defer the actual copy until necessary.
• When a variable is assigned or passed to a function, PHP does not create a separate copy of the
variable's data. Instead, it shares the same data in memory.
• If a change is made to one of the variables that share the same data, PHP duplicates the data at
that point, ensuring that the other variables are not affected. This deferred duplication is known as
"copy-on-write."

Example:

$a = [1, 2, 3]; // $a references an array


$b = $a; // $b references the same array

// Only when a change is made, the array is duplicated


$a[] = 4; // $a is modified, and a copy of the array is made
echo implode(', ', $b); // $b remains unaffected
• Copy-on-write is an efficient technique because it optimizes memory usage, avoiding unnecessary
duplication of data. However, it relies on the understanding that changes to a variable are rare
compared to reading its value.

Both reference counting and copy-on-write are important techniques used by PHP's memory management
system to minimize memory consumption and efficiently handle variable and object management. It's
essential for PHP developers to be aware of these mechanisms to write efficient and memory-friendly
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 Precendence :

• 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.

Understanding the number of operands, operator precedence, operator associativity, and implicit casting
is crucial for writing correct and efficient PHP code. It helps ensure that your expressions are evaluated as
intended and that data types are handled appropriately during operations.

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 (+):
• 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!";
$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:

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
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 = ~$a
5. 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

Bitwise operators are often used in scenarios where fine-grained control over individual bits is
required, such as setting or clearing flags in a bitfield, encoding or decoding data, and optimizing
memory usage. They are especially useful in systems programming and embedded development
where memory and performance are critical considerations.

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 false
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;
$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. They help make decisions and implement
branching logic by evaluating the truth or falsehood of expressions. Understanding how to use
logical operators is crucial for effective programming in PHP.

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. These operators allow you to
control how data is treated in your code and can help prevent unexpected results due to
automatic type coercion. 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. They provide explicit control over type conversions, especially when you want to change a
value's type to match the requirements of a particular operation or function.

9. Assignment Operator :
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. They provide a convenient way to update variable values without
the need for additional expressions.

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):
• 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('nonexistentfile.txt');

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 them
effectively and consider their implications when designing your applications.
➢ 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.

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++;
}

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>";
}

6. try-catch Block:
• The try and catch blocks are used for exception handling. Code within the try block is
executed, and if an exception is thrown, it's caught in the catch block.

Syntax :
try {
// Code that might throw an exception
} catch (ExceptionType $e) {
// Code to handle the exception
}

Example :
try {
$result = 10 / 0; // Division by zero
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}

7. declare Statement:
• The declare statement is used to set certain options or directives that affect the behavior of
a block of code.

Example :
declare(strict_types=1); // Enforce strict type checking
function add(int $a, int $b) {
return $a + $b;
}
8. exit and return Statements:
• The exit statement is used to terminate the script, while the return statement is used to
return a value from a function.

Example :
if ($error) {
exit("An error occurred.");
}

function add($a, $b) {


return $a + $b;
}

9. goto Statement (PHP 5.3 and later):


• The goto statement allows you to jump to a specific label within your code.

Example :
$value = 5;
if ($value < 0) {
goto negative;
}
echo "Value is positive.";
negative:
echo "Value is negative.";

Please note that the use of the goto statement is generally discouraged in modern programming,
as it can lead to difficult-to-maintain code. The other flow control statements are more commonly
used and provide structured and organized control over program execution.

➢ Including Code :
In PHP, you can include code from one file within another file using various techniques. This is a
powerful way to reuse code, organize your project into manageable parts, and maintain code
modularity. Here are the primary methods for including code in PHP:

1. include Statement:
• The include statement is used to include and execute code from another file. If the
included file is not found, it generates a warning but allows the script to continue.
• Syntax:
include 'filename.php';
Example :
include 'header.php';
// Rest of your PHP code
include 'footer.php';

2. require Statement:
• The require statement is similar to include, but if the included file is not found, it generates a
fatal error and terminates the script.
• Syntax:
require 'filename.php';

Example :
require 'config.php';
// Rest of your PHP code
require 'database.php';

3. include_once and require_once Statements:


• These statements work similarly to include and require, respectively, but they ensure that
the same file is not included or required multiple times in a single script. This can prevent
issues with redeclaration of functions or classes.
• Syntax:
include_once 'filename.php';
require_once 'filename.php';

Example :
include_once 'functions.php';
// Rest of your PHP code
include_once 'functions.php';

4. include and require with Absolute Paths:


• You can use absolute paths to include or require files from anywhere on your server, which
can be useful for including files from different directories.
• Example:
include '/var/www/html/includes/header.php';
require 'C:/xampp/htdocs/config.php';

5. Autoloading Classes:
• For object-oriented PHP code, you can use an autoloader to automatically include class files
as needed. This is commonly used with PHP frameworks and object-oriented code.
• Example (using Composer's autoloader):
require 'vendor/autoload.php';
6. eval Function (Not Recommended):
• The eval function can execute PHP code stored as a string, but it's generally not
recommended due to security and maintainability concerns.
• Syntax:
$code = 'echo "Hello, World!";';
eval($code);

When including or requiring code in PHP, it's essential to consider the directory structure of your
project, use relative or absolute paths appropriately, and ensure that the included files exist.
Additionally, take care to handle errors gracefully and ensure that included files don't redeclare
functions or classes.

➢ Embedding PHP in Web Pages :

PHP can be embedded in web pages using various styles and methods. Here are different ways to
embed PHP in web pages, including standard XML-style, SGML-style, ASP-style, script-style, and
echoing content directly:

1. Standard (XML) Style:


• In the standard XML-style, PHP code is embedded within XML-like tags, similar to how you
might embed JavaScript in HTML.
• Syntax:
<?php
// Your PHP code here
?>

Example :
<!DOCTYPE html>
<html>
<head>
<title>XML-Style PHP</title>
</head>
<body>
<p><?php echo "Hello, World!"; ?></p>
</body>
</html>

2. SGML Style:
• In SGML-style, PHP code is enclosed within HTML-like comment tags, which makes it easy
to read but may not be as syntactically clean.
• Syntax:
<!--
Your PHP code here
-->

Example:
<!DOCTYPE html>
<html>
<head>
<title>SGML-Style PHP</title>
</head>
<body>
<p><!--
<?php
echo "Hello, World!";
?>
--></p>
</body>
</html>

3. ASP Style:
• PHP can also be embedded in a style similar to ASP (Active Server Pages). PHP code is
enclosed within <% and %> tags.
• Syntax:
<%
// Your PHP code here
%>

Example:
<!DOCTYPE html>
<html>
<head>
<title>ASP-Style PHP</title>
</head>
<body>
<p>
<%
echo "Hello, World!";
%>
</p>
</body>
</html>
4. Script Style:
• In script style, PHP code is embedded using the <script> element, similar to JavaScript.
• Syntax:
<script language="php">
// Your PHP code here
</script>

Example:
<!DOCTYPE html>
<html>
<head>
<title>Script-Style PHP</title>
</head>
<body>
<p>
<script language="php">
echo "Hello, World!";
</script>
</p>
</body>
</html>

5. Echoing Content Directly:


• You can also directly echo content from PHP within HTML, without enclosing it in PHP tags.
• Example:
<!DOCTYPE html>
<html>
<head>
<title>Direct PHP Echo</title>
</head>
<body>
<p>
<?php echo "Hello, World!"; ?>
</p>
</body>
</html>

The choice of style largely depends on your preference and the structure of your web page. The
standard XML-style (<?php ?>) is the most common and widely used way to embed PHP in web
pages. Other styles are less common and may have limitations or affect the readability and
maintainability of your code.

You might also like