0% found this document useful (0 votes)
0 views39 pages

Unit II PHP

PHP is a widely-used server-side scripting language that enables dynamic web content, database management, and user authentication, among other functionalities. It has evolved significantly since its inception in 1994, with numerous versions introducing enhanced features and performance improvements. PHP supports various data types, including scalar, compound, and special types, and is utilized in diverse applications such as content management systems and e-commerce platforms.
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)
0 views39 pages

Unit II PHP

PHP is a widely-used server-side scripting language that enables dynamic web content, database management, and user authentication, among other functionalities. It has evolved significantly since its inception in 1994, with numerous versions introducing enhanced features and performance improvements. PHP supports various data types, including scalar, compound, and special types, and is utilized in diverse applications such as content management systems and e-commerce platforms.
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/ 39

1 What Does PHP Do?

PHP is a server-side scripting language, which means that a web server executes the
PHP script and then sends the resulting HTML to the browser. PHP is used in over 75% of
websites that use a server-side programming language.
PHP, or Hypertext Preprocessor, is a scripting language that can perform a variety of
tasks for web development, including:
 Dynamic content: PHP can generate dynamic web pages that change based on user
input or other factors
 Database management: PHP can store, delete, and modify data in a database
 Form handling: PHP can collect and validate form data
 Cookies: PHP can send and receive cookies
 User authentication: PHP can store and retrieve usernames and passwords, and
support two-step verification
 Data encryption: PHP can encrypt data
 File management: PHP can create, open, read, write, delete, and close files on the
server
 Emailing: PHP can send emails

Advantages:
 Platform Independent
 Open source and dynamic Library support
 Organized
 Database Connectivity
 Easy to understand and code
 Gives Web Developer More Control
 Easy integration and consistency
 Maintenance
 Stability
 Performance
 Reliability
 Scalability
 Compatibility
Disadvantages of PHP
 Inconsistency
 Security Concerns
 Performance
 Lack of Modern Features
 Scalability Challenges
 Not Suitable for Large-Scale Applications
 Limited Object-Oriented Programming (OOP) Support

2 A Brief History of PHP


PHP history dates back to the early days of the web, and it have 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.

Syntax of PHP
<?php
// PHP code goes here
?>
Basic Example of PHP
<html>

<head>
<title>PHP Hello World</title>
</head>

<body>
<?php echo "Hello, World! This is PHP code";?>
</body>

</html>

Output:
Hello, World! This is PHP code

Characteristics of PHP
 PHP code is executed in the server.
 It can be integrated with many databases such as Oracle, Microsoft SQL Server,
MySQL, PostgreSQL, Sybase, and Informix.
 It is powerful to hold a content management system like WordPress and can be used
to control user access.
 It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.
 Websites like www.facebook.com and www.yahoo.com are also built on PHP.
 One of the main reasons behind this is that PHP can be easily embedded in HTML
files and HTML codes can also be written in a PHP file.
 The thing that differentiates PHP from the client-side language like HTML is, that
PHP codes are executed on the server whereas HTML codes are directly rendered on
the browser. PHP codes are first executed on the server and then the result is returned
to the browser.
 The only information that the client or browser knows is the result returned after
executing the PHP script on the server and not the actual PHP codes present in the
PHP file. Also, PHP files can support other client-side scripting languages like CSS
and JavaScript.

Features of PHP
 Open-Source and Free: PHP is firstly open source which means anyone can use
PHP code without any licensing. Along with this one can run PHP on any operating
system like Windows, macOS, Linux, Unix and more.
 PHP Server-Side Scripting: PHP code executes on the server before sending
HTML content to the user's browser, allowing for the dynamic generation of web
pages and handling user interactions.
 Interpreted language: PHP code is interpreted line by line, eliminating the need for
compilation and simplifying development and testing processes.
 Database connectivity: PHP integrates seamlessly with various databases like
MySQL, PostgreSQL, and Oracle, facilitating data storage and retrieval for web
applications.
 Object-oriented programming (OOP): PHP supports OOP concepts like classes,
objects, inheritance, and polymorphism, enabling better code organization and
modularity.
 Built-in functions: PHP comes with a rich set of built-in functions for various tasks
such as string manipulation, date and time handling, file handling, and more,
reducing the need for external libraries.
 Session management: PHP allows for user session management, enabling
personalized experiences and storing user data across multiple page visits.
 Security features: While security considerations are essential for any development
language, PHP offers several built-in security features and best practices to help
mitigate vulnerabilities
 Dynamic Typing: PHP is dynamically typed, meaning you don’t need to declare the
data type of a variable explicitly.
 Cross-Platform: PHP runs on various platforms, making it compatible with different
operating systems.
 Database Integration: PHP provides built-in support for interacting with databases,
such as MySQL, PostgreSQL, and others.
Applications of PHP
PHP is versatile and can be used in a variety of web development scenarios,
including:

 Dynamic Web Pages: Generating dynamic content based on user interaction or other
conditions.
 Content Management Systems (CMS): Many popular CMSs like WordPress,
Joomla, and Drupal are built with PHP.
 E-commerce Platforms: PHP is commonly used to develop e-commerce websites
due to its database integration capabilities.
 Web Applications: PHP is used for creating feature-rich web applications such as
social media platforms, forums, and customer relationship management (CRM)
systems.
 API Development: PHP can be used to create APIs for web and mobile applications.

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

4 Introduction to Data Types


PHP data types are used to hold different types of data or values. PHP supports 8
primitive data types that can be categorized further in 3 types:
1. Scalar Types (predefined)
2. Compound Types (user-defined)
3. Special Types
1 PHP Data Types: Scalar Types
It holds only single value. There are 4 scalar data types in PHP.
1. Boolean
2. integer
3. float
4. string

PHP Boolean
Booleans are the simplest data type works like switch. It holds only two
values: TRUE (1) or FALSE (0). It is often used with conditional statements. If the condition
is correct, it returns TRUE otherwise FALSE.
Example:
1. <?php
2. if (TRUE)
3. echo "This condition is TRUE.";
4. if (FALSE)
5. echo "This condition is FALSE.";
6. ?>
Output:
This condition is TRUE.
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole
numbers, i.e., numbers without fractional part or decimal points.
Rules for integer:
o An integer can be either positive or negative.
o An integer must not contain decimal point.
o Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).
o The range of an integer must be lie between 2,147,483,648 and 2,147,483,647 i.e., -
2^31 to 2^31.
Example:
1. <?php
2. $dec1 = 34;
3. $oct1 = 0243;
4. $hexa1 = 0x45;
5. echo "Decimal number: " .$dec1. "</br>";
6. echo "Octal number: " .$oct1. "</br>";
7. echo "HexaDecimal number: " .$hexa1. "</br>";
8. ?>
Output:
Decimal number: 34
Octal number: 163
HexaDecimal number: 69
PHP Float
A floating-point number is a number with a decimal point. Unlike integer, it can hold
numbers with a fractional or decimal point, including a negative or positive sign.
Example:
1. <?php
2. $n1 = 19.34;
3. $n2 = 54.472;
4. $sum = $n1 + $n2;
5. echo "Addition of floating numbers: " .$sum;
6. ?>
Output:
Addition of floating numbers: 73.812
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers, and
even special characters. String values must be enclosed either within single quotes or
in double quotes. But both are treated differently. To clarify this, see the example below:
Example:
1. <?php
2. $company = "Javatpoint";
3. //both single and double quote statements will treat different
4. echo "Hello $company";
5. echo "</br>";
6. echo 'Hello $company';
7. ?>
Output:
Hello Javatpoint
Hello $company
2 PHP Data Types: Compound Types
It can hold multiple values. There are 2 compound data types in PHP.
1. array
2. object
PHP Array
An array is a compound data type. It can store multiple values of same data type in a
single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and valu
es
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=>
string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
1. <?php
2. class bike {
3. function model() {
4. $model_name = "Royal Enfield";
5. echo "Bike Model: " .$model_name;
6. }
7. }
8. $obj = new bike();
9. $obj -> model();
10. ?>
Output:
Bike Model: Royal Enfield
3 PHP Data Types: Special Types
There are 2 special data types in PHP.
1. resource
2. NULL

PHP Resource
Resources are not the exact data type in PHP. Basically, these are used to store some
function calls or references to external PHP resources. For example - a database call. It is an
external resource.This is an advanced topic of PHP, so we will discuss it later in detail with
examples.
PHP Null
Null is a special data type that has only one value: NULL. There is a convention of
writing it in capital letters as it is case sensitive. The special type of data type NULL defined
a variable with no value.
Example:
<?php

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

// return data type


var_dump($nm);

?>
Output:
NULL

5 Variables
PHP Variables are one of the most fundamental concepts in programming. It is used
to store data that can be accessed and manipulated within your code. Variables in PHP are
easy to use, dynamically typed and essential for creating dynamic, interactive web
applications.
Declaring Variables in PHP
To declare a variable in PHP, you simply assign a value to it using the $ symbol
followed by the variable name. PHP variables are case-sensitive and must start with a letter or
an underscore, followed by any number of letters, numbers, or underscores.
Example
<?php
$name = "XYZ"; // String
$age = 30; // Integer
$salary = 45000.50; // Float
$isEmployed = true; // Boolean
?>

Variable Naming Conventions


In PHP, it’s important to follow certain naming conventions for PHP variables to
ensure readability and maintainability:
 Start with a Letter or Underscore: Variable names must begin with a letter or an
underscore (_), not a number.
 Use Descriptive Names: Variable names should be descriptive of their purpose, e.g.,
$userName, $totalAmount.
 Case Sensitivity: PHP variable names are case-sensitive, meaning $name and $Name
are different variables.
 Avoid Reserved Words: Do not use PHP reserved words or keywords as variable
names (e.g., function, class, echo).
Example of Valid and Invalid Variable Names
<?php
$firstName = "Alice"; // Valid
$_age = 25; // Valid
$2ndPlace = "Bob"; // Invalid: Cannot start with a number
$class = "Physics"; // Valid, but avoid reserved words
?>
6 Variable Scope
The scope of a variable refers to where it can be accessed within the code. PHP
variables can have local, global, static, or superglobal scope.
1. Local Scope or Local Variable
Variables declared within a function have local scope and cannot be accessed outside
the function. Any declaration of a variable outside the function with the same name (as within
the function) is a completely different variable.
Example: This example shows the local variable in PHP.
<?php
$num = 60;
function local_var() {
// This $num is local to this function
// The variable $num outside the function
// is a completely different
$num = 50;
echo "Variable num inside function is: $num \n";
}
local_var();
// The $num outside function is a completely
// different from inside local_var()
echo "Variable num outside function is: $num";
?>
Output
Variable num inside function is: 50
Variable num outside function is: 60
2. Global Scope or Global Variable
The variables declared outside a function are called global variables. These variables
can be accessed directly outside a function. To get access within a function we need to use
the “global” keyword before the variable to refer to the global variable.
Example: This example shows the Global Variables in PHP.
<?php
$num = 20;
// Function to demonstrate use of global variable
function global_var() {
// We have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function: $num \n";
}
global_var();
echo "Variable num outside function: $num \n";
?>
Output
Variable num inside function: 20
Variable num outside function: 20
3. Static Variables
It is the characteristic of PHP to delete the variable. Once it completes its execution
and the memory is freed. But sometimes we need to store the variables even after the
completion of function execution. To do this, we use the static keywords and the variables are
then called static variables. PHP associates a data type depending on the value for the
variable.
Example: This example shows the Static variable in PHP.
<?php
// Function to demonstrate static variables
function static_var() {
// Static Variable
static $num = 5;
$sum = 2;

$sum++;
$num++;

echo $num, "\n";


echo $sum, "\n";
}
// First function call
static_var();
// Second function call
static_var();
?>
Output
6
3
7
3

4. Superglobals
Superglobals are built-in arrays in PHP that are accessible from anywhere in the
script, including within functions. Common superglobals include $_GET, $_POST,
$_SESSION, $_COOKIE, $_SERVER, and $_GLOBALS.
<?php
// Using $_SERVER superglobal to
// get server information
echo $_SERVER['SERVER_NAME'];
?>

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

7 Introduction to Expressions and Operators


1 Operators
Operators are used to performing operations on some values. In other words, we can
describe operators as something that takes some values, performs some operation on them,
and gives a result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes
two values 1 and 2, performs an addition operation on them to give 3.
PHP provides us with many operators to perform such operations on various operands
or variables, or values. These operators are nothing but symbols needed to perform operations
of various types. Given below are the various groups of operators:
 Arithmetic Operators
 Logical or Relational Operators
 Comparison Operators
 Conditional or Ternary Operators
 Assignment Operators
 Spaceship Operators (Introduced in PHP 7)
 Array Operators
 Increment/Decrement Operators
 String Operators
Arithmetic Operators:
The arithmetic operators are used to perform simple mathematical operations like
addition, subtraction, multiplication, etc. Below is the list of arithmetic operators along with
their syntax and operations in PHP.

Operator Name Syntax Operation

+ Addition $x + $y Sum the operands

– Subtraction $x – $y Differences the operands

* Multiplication $x * $y Product of the operands

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

** Exponentiation $x ** $y $x raised to the power $y

% Modulus $x % $y The remainder of the operands


Example: This example explains the arithmetic operator in PHP.
<?php
// Define two numbers
$x = 10;
$y = 3;

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

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

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

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

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

// Modulus
echo "Modulus: " . ($x % $y) . "\n";
?>
Output
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333
Exponentiation: 1000
Modulus: 1
Logical or Relational Operators:
These are basically used to operate with conditional statements and expressions.
Conditional statements are based on conditions. Also, a condition can either be met or cannot
be met so the result of a conditional statement can either be true or false. Here are the logical
operators along with their syntax and operations in PHP.

Operator Name Syntax Operation

Logical $x and True if both the operands are true else


and
AND $y false

True if either of the operands is true


or Logical OR $x or $y
else false
Operator Name Syntax Operation

Logical $x xor True if either of the operands is true


xor
XOR $y and false if both are true

Logical $x && True if both the operands are true else


&&
AND $y false

True if either of the operands is true


|| Logical OR $x || $y
else false

Logical
! !$x True if $x is false
NOT

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

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

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


echo "xor Success \n";

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


echo "&& Success \n";

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

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

Operator Name Syntax Operation

Returns True if both the


== Equal To $x == $y
operands are equal

Returns True if both the


!= Not Equal To $x != $y
operands are not equal

Returns True if both the


<> Not Equal To $x <> $y
operands are unequal

Returns True if both the


$x ===
=== Identical operands are equal and are of
$y
the same type

Returns True if both the


!== Not Identical $x == $y operands are unequal and are
of different types

Returns True if $x is less than


< Less Than $x < $y
$y

Returns True if $x is greater


> Greater Than $x > $y
than $y

Less Than or Returns True if $x is less than


<= $x <= $y
Equal To or equal to $y

Greater Than or Returns True if $x is greater


>= $x >= $y
Equal To than or equal to $y

Example: This example describes the comparison operator in PHP.


<?php
$a = 80;
$b = 50;
$c = "80";
// Here var_dump function has been used to
// display structured information. We will learn
// about this function in complete details in further
// articles.
var_dump($a == $c) + "\n";
var_dump($a != $b) + "\n";
var_dump($a <> $b) + "\n";
var_dump($a === $c) + "\n";
var_dump($a !== $c) + "\n";
var_dump($a < $b) + "\n";
var_dump($a > $b) + "\n";
var_dump($a <= $b) + "\n";
var_dump($a >= $b);
?>
Output:
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)
bool(false)
bool(true)

Conditional or Ternary Operators:


These operators are used to compare two values and take either of the results
simultaneously, depending on whether the outcome is TRUE or FALSE.
Syntax:
$var = (condition)? value1 : value2;
Here, the condition will either evaluate as true or false. If the condition evaluates to True,
then value1 will be assigned to the variable $var otherwise value2 will be assigned to it.

Operator Name Operation

If the condition is true? then $x : or else $y. This means that if


?: Ternary the condition is true then the left result of the colon is accepted
otherwise the result is on right.

Example: This example describes the Conditional or Ternary operators in PHP.


<?php
$x = -12;
echo ($x > 0) ? 'The number is positive' : 'The number is negative';
?>
Output:
The number is negative

Assignment Operators:
These operators are used to assign values to different variables, with or without mid-
operations. Here are the assignment operators along with their syntax and operations, which
PHP provides for the operations.
Operator Name Syntax Operation

Operand on the left obtains the


= Assign $x = $y value of the operand on the
right

$x += Simple Addition same as $x =


+= Add then Assign
$y $x + $y

Simple subtraction same as $x


-= Subtract then Assign $x -= $y
= $x – $y

$x *= Simple product same as $x =


*= Multiply then Assign
$y $x * $y

Divide then Assign Simple division same as $x =


/= $x /= $y
(quotient) $x / $y

Divide then Assign $x %= Simple division same as $x =


%= (remainder) $y $x % $y

Example: This example describes the assignment operator in PHP.


<?php
// Simple assign operator
$y = 75;
echo $y, "\n";

// Add then assign operator


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

// Subtract then assign operator


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

// Multiply then assign operator


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

// Divide then assign(quotient) operator


$y = 100;
$y /= 5;
echo $y, "\n";
// Divide then assign(remainder) operator
$y = 50;
$y %= 5;
echo $y;
?>
Output:
75
300
60
600
20
0

Spaceship Operators:
PHP 7 has introduced a new kind of operator called spaceship operator. The spaceship
operator or combined comparison operator is denoted by “<=>“. These operators are used to
compare values but instead of returning the boolean results, it returns integer values. If both
the operands are equal, it returns 0. If the right operand is greater, it returns -1. If the left
operand is greater, it returns 1. The following table shows how it works in detail:

Operator Syntax Operation

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

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

Identical to -1 (right is greater) or identical to 0 (if both


$x <= $y $x <=> $y
are equal)

Identical to 1 (if left is greater) or identical to 0 (if both


$x >= $y $x <=> $y
are equal)

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

$x != $y $x <=> $y Not Identical to 0

Example: This example illustrates the use of the spaceship operator in PHP.
<?php
$x = 50;
$y = 50;
$z = 25;
echo $x <=> $y;
echo "\n";

echo $x <=> $z;


echo "\n";

echo $z <=> $y;


echo "\n";

// We can do the same for Strings


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

echo $x <=> $y;


echo "\n";

echo $x <=> $y;


echo "\n";

echo $y <=> $x;


?>
Output:
0
1
-1
1
1
-1

Array Operators:
These operators are used in the case of arrays. Here are the array operators along with
their syntax and operations that PHP provides for the array operation.

Operator Name Syntax Operation

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

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

!= Inequality $x != $y Returns True if both are unequal

$x === Returns True if both have the same key-value


=== Identity
$y pair in the same order and of the same type

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


!==
Identity $y other
Operator Name Syntax Operation

<> Inequality $x <> $y Returns True if both are unequal

Example: This example describes the array operation in PHP.


<?php
$x = array("k" => "Car", "l" => "Bike");
$y = array("a" => "Train", "b" => "Plane");

var_dump($x + $y);
var_dump($x == $y) + "\n";
var_dump($x != $y) + "\n";
var_dump($x <> $y) + "\n";
var_dump($x === $y) + "\n";
var_dump($x !== $y) + "\n";
?>
Output:
array(4) {
["k"]=>
string(3) "Car"
["l"]=>
string(4) "Bike"
["a"]=>
string(5) "Train"
["b"]=>
string(5) "Plane"
}
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)

Increment/Decrement Operators:
These are called the unary operators as they work on single operands. These are used
to increment or decrement values.

Operator Name Syntax Operation

First increments $x by one, then


++ Pre-Increment ++$x
return $x

First decrements $x by one, then


— Pre-Decrement –$x
return $x
Operator Name Syntax Operation

First returns $x, then increment it by


++ Post-Increment $x++
one

First returns $x, then decrement it by


— Post-Decrement $x–
one

Example: This example describes the Increment/Decrement operators in PHP.


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

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

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

$x = 2;
echo $x--, " First prints then decrements \n";
echo $x;
?>
Output:

3 First increments then prints


3
2 First prints then increments
3
1 First decrements then prints
1
2 First prints then decrements
1

String Operators:
This operator is used for the concatenation of 2 or more strings using the
concatenation operator (‘.’). We can also use the concatenating assignment operator (‘.=’) to
append the argument on the right side to the argument on the left side.
Operator Name Syntax Operation

. Concatenation $x.$y Concatenated $x and $y

Concatenation and First concatenates then


.= $x.=$y
assignment assigns, same as $x = $x.$y

Example: This example describes the string operator in PHP.


<?php
$x = "Books";
$y = "for";
$z = "Books!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>
Output:
BooksforBooks!!!
BooksforBooks!!!

2 Expressions
Almost everything in a PHP script is an expression. Anything that has a value is an
expression. In a typical assignment statement ($x=100), a literal value, a function or operands
processed by operators is an expression, anything that appears to the right of assignment
operator (=)

Syntax
$x=100; //100 is an expression
$a=$b+$c; //b+$c is an expression
$c=add($a,$b); //add($a,$b) is an expresson
$val=sqrt(100); //sqrt(100) is an expression
$var=$x!=$y; //$x!=$y is an expression

Expression with ++ and -- operators


These operators are called increment and decrement operators respectively. They are
unary operators, needing just one operand and can be used in prefix or postfix manner,
although with different effect on value of expression
Both prefix and postfix ++ operators increment value of operand by 1 (whereas --
operator decrements by 1). However, when used in assignment expression, prefix
makesincremnt/decrement first and then followed by assignment. In case of postfix,
assignment is done before increment/decrement
Uses postfix ++ operator
1 Example
<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 10
Whereas following example uses prefix increment operator in assignment
2 Example
<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>
Output
This produces following result
x = 11 y = 11
Expression with Ternary conditional operator
Ternary operator has three operands. First one is a logical expression. If it is TRU,
second operand expression is evaluated otherwise third one is evaluated
Example
<?php
$marks=60;
$result= $marks<50 ? "fail" : "pass";
echo $result;
?>
Output
Following result will be displayed
Pass

8 Flow-Control Statements
Flow control statements in PHP are used to control the order in which code is
executed. There are three types of flow control statements in PHP:
 Conditional statements: These statements execute a block of code based on certain
conditions. Examples include if, else, and switch statements.
 Loop statements: These statements execute a block of code repeatedly based on
certain conditions. Examples include for, while, do-while, and foreach loops.
 Jump statements: These statements transfer control to another part of the code.

Conditional statements
PHP provides us with four conditional statements:
 if statement
 if…else statement
 if…elseif…else statement
 switch statement
1 if Statement:
This statement allows us to set a condition. On being TRUE, the following block of
code enclosed within the if clause will be executed.
Syntax :
if (condition){
// if TRUE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}
?>
Output:
The number is positive
Flowchart:

2 if…else Statement:
We understood that if a condition will hold i.e., TRUE, then the block of code within
if will be executed. But what if the condition is not TRUE and we want to perform an action?
This is where else comes into play. If a condition is TRUE then if block gets executed,
otherwise else block gets executed.
Syntax:
if (condition) {
// if TRUE then execute this code
}
else{
// if FALSE then execute this code
}
Example:
<?php
$x = 12;
if ($x > 0) {
echo "The number is positive";
}else{
echo "The number is negative";
}
?>
Output:
The number is negative

Flowchart:

3 if…elseif…else Statement:
This allows us to use multiple if…else statements. We use this when there are
multiple conditions of TRUE cases.
Syntax:
if (condition) {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
elseif {
// if TRUE then execute this code
}
else {
// if FALSE then execute this code
}
Example:
<?php
$x = "August";

if ($x == "January") {
echo "Happy Republic Day";
}
elseif ($x == "August") {
echo "Happy Independence Day!!!";
}

else{
echo "Nothing to show";
}
?>
Output:
Happy Independence Day!!!

Flowchart:

4 switch Statement:
The “switch” performs in various cases i.e., it has various cases to which it matches
the condition and appropriately executes a particular case block. It first evaluates an
expression and then compares with the values of each case. If a case matches then the same
case is executed. To use switch, we need to get familiar with two different keywords namely,
break and default.
1. The break statement is used to stop the automatic control flow into the next cases and
exit from the switch case.
2. The default statement contains the code that would execute if none of the cases match.
Syntax:
switch(n) {
case statement1:
code to be executed if n==statement1;
break;
case statement2:
code to be executed if n==statement2;
break;
case statement3:
code to be executed if n==statement3;
break;
case statement4:
code to be executed if n==statement4;
break;
......
default:
code to be executed if n != any case;

Example:
<?php
$n = "February";
switch($n) {
case "January":
echo "Its January";
break;
case "February":
echo "Its February";
break;
case "March":
echo "Its March";
break;
case "April":
echo "Its April";
break;
case "May":
echo "Its May";
break;
case "June":
echo "Its June";
break;
case "July":
echo "Its July";
break;
case "August":
echo "Its August";
break;
case "September":
echo "Its September";
break;
case "October":
echo "Its October";
break;
case "November":
echo "Its November";
break;
case "December":
echo "Its December";
break;
default:
echo "Doesn't exist";
}
?>
Output:
Its February
Flowchart:

Loop statements
PHP Loops are used to repeat a block of code multiple times based on a given
condition. PHP provides several types of loops to handle different scenarios, including while
loops, for loops, do…while loops, and foreach loops.
PHP provides us with four Loop statements:
 for Loop
 while Loop
 do-while Loop
 foreach Loop

1 PHP for Loop


PHP for loop is used when you know exactly how many times you want to iterate
through a block of code. It consists of three expressions:
 Initialization: Sets the initial value of the loop variable.
 Condition: Checks if the loop should continue.
 Increment/Decrement: Changes the loop variable after each iteration.
Syntax
for ( Initialization; Condition; Increment/Decrement ) {
// Code to be executed
}
Example: Printing numbers from 1 to 5 using for loop.
<?php

// Code to illustrate for loop


for ($num = 1; $num <= 5; $num += 1) {
echo $num . " ";
}

?>
Output
12345

2 PHP while Loop


The while loop is also an entry control loop like for loops. It first checks the condition
at the start of the loop and if its true then it enters into the loop and executes the block of
statements, and goes on executing it as long as the condition holds true.

Syntax
while ( condition ) {
// Code is executed
}

Example: Printing numbers from 1 to 5.


<?php

$num = 1;

while ($num <= 5) {


echo $num . " ";
$num++;
}

?>
Output
12345

3 PHP do-while Loop


The do-while loop is an exit control loop which means, it first enters the loop,
executes the statements, and then checks the condition. Therefore, a statement is executed at
least once using the do…while loop. After executing once, the program is executed as long as
the condition holds true.
Syntax
do {
// Code is executed
} while ( condition );
Example: Printing numbers from 1 to 5.
<?php

$num = 1;

do {
echo $num . " ";
$num++;
} while ($num <= 5);

?>
Output
12345

4 PHP foreach Loop


This foreach loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.

Syntax:
foreach ( $array as $key => $value ) {
// Code to be executed
}

Example: Iterating through an array


<?php

// foreach loop over an array


$arr = array (10, 20, 30, 40, 50, 60);

foreach ($arr as $val) {


echo $val . " ";
}

echo "\n";

// foreach loop over an array with keys


$ages = array(
"John" => 25,
"Alice" => 30,
"Bob" => 22
);

foreach ($ages as $name => $age) {


echo $name . " => " . $age . "\n";
}

?>
Output
10 20 30 40 50 60
John => 25
Alice => 30
Bob => 22

Jump statements
Jump statement is a control flow statement in programming that alters the normal
sequential execution of code by transferring program control to a different part of the code.
Jump statements include commands like "break," "continue," "return," and "goto," each
serving specific purposes:
 break: Terminates the current loop iteration or exits a switch statement, transferring
control to the statement immediately following the loop or switch block.
 continue: Skips the rest of the current loop iteration and proceeds to the next iteration
of the loop.
 return: Exits a function prematurely and returns a value, if specified, to the caller.
 goto: Allows transferring control to a labeled statement within the same function or
block, though its usage is discouraged in modern programming due to potential
complications in code readability and maintenance.

1 PHP Break
PHP break statement breaks the execution of the current for, while, do-while, switch,
and for-each loop. The break keyword immediately ends the execution of the loop or switch
structure. It breaks the current flow of the program at the specified condition and program
control resumes at the next statements outside the loop. The break statement can be used in
all types of loops such as while, do-while, for, foreach loop, and also with switch case.

Syntax
jump statement;
break;

2 PHP continue statement


The PHP continue statement is used to continue the loop. It continues the current flow
of the program and skips the remaining code at the specified condition. The continue
statement is used within looping and switch control structure when you immediately jump to
the next iteration. The continue statement can be used with all types of loops such as - for,
while, do-while, and foreach loop. The continue statement allows the user to skip the
execution of the code for the specified condition.
Syntax
jump-statement;
continue;

3 PHP goto Statement


The goto statement is used to jump to another section of a program. It is sometimes
referred to as an unconditional jump statement. The goto statement can be used to jump from
anywhere to anywhere within a function.
Flowchart of goto statement:

Syntax:
statement_1;
if (expr)
goto label;
statement_2;
statement_3;
label: statement_4;

Example
#include <stdio.h>
int getResult()
{
int result = 10;
if (result > 0) {
return result; // Return a positive value
}
}

int main()
{
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the remaining code for i=3
}
printf("%d ", i);
if (i == 4) {
break; // Exit the loop when i=4
}
}

printf("%d ", getResult());


int num = 5;
if (num == 5) {
goto exit; // Unconditionally jump to the 'exit'
// label
}
exit:
printf("Using goto statement.\n");

return 0;
}
9 Working with include and require construct
It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with include or require statement.
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';
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>
Output
Welcome to my home page!
Some text.
Some more text.

PHP include vs. require

The require statement is also used to include a file into the PHP code.
However, there is one big difference between include and require; when a file is
included with the include statement and PHP cannot find it, the script will continue to
execute:
Example
<html>
<body>
<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
Output
Welcome to my home page!
I have a
If we do the same example using the require statement, the echo statement will not be
executed because the script execution dies after the require statement returned a fatal error:
Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>
Output
Welcome to my home page!
Difference between require() and include()

include()
require()

The include() function does not stop the The require() function will stop the
execution of the script even if any error execution of the script when an
occurs. error occurs.

The include() function does not give a The require() function gives a fatal
fatal error. error

The include() function is mostly used


The require() function is mostly
when the file is not required and the
used when the file is mandatory for
application should continue to execute its
the application.
process when the file is not found.

The require() will produce a fatal


The include() function will only produce
error (E_COMPILE_ERROR)
a warning (E_WARNING) and the script
along with the warning and the
will continue to execute.
script will stop its execution.

The require() function is more in


recommendation and considered
The include() function generate various
better whenever we need to stop the
functions and elements that are reused
execution incase of availability of
across many pages taking a longer time
file, it also saves time avoiding
for the process completion.
unnecessary inclusions and
generations.

10 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.
Components of SGML:
 SGML provides a way of describing the relationships between these entities,
elements, and attributes, and tells the computer how it can recognize the
component parts of a document and it is based on the concept of a document
being composed of a series of entities (object).
 It provides rules that allow the computer to recognize where the various
elements of a text entity start and end.
 Document Type Definition (DTD) in SGML is used to describe each element
of the document in a form that the computer can understand.
SGML is the simplest medium to produce files that can be read by people and
exchanged between machines and applications in a straightforward manner. It is
easy to understand by the human as well as the machine.
Structure of SGML:
<mainObject>
<subObject>

</subObject>
</mainObject>
The extension of SGML files is:
File_Name.sg
ml
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