Php - (Unit - i) Notes
Php - (Unit - i) Notes
➢ 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.
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.
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.
<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.
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.
• 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.
• 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.
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.
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.
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.
##########################################
####### 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.
➢ 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.
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:
2. Control Structures:
3. Data Types:
5. Error Handling:
6. Namespaces:
7. Other Keywords:
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.
• 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;
}
}
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:
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:
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:
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:
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.
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.
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:
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:
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.
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:
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:
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:
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
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:
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.
6. Instanceof Operator:
• The instanceof operator is used to check if an object is an instance of a particular class.
• Example:
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.");
}
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';
Example :
include_once 'functions.php';
// Rest of your PHP code
include_once 'functions.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.
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:
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>
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.