Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Unit-1 PHP

This document provides an introduction to PHP, detailing its features, history, and installation process. PHP is a server-side scripting language that is open-source and easy to learn, making it suitable for web development. The document also covers basic PHP syntax, data types, and how to embed PHP code within HTML.

Uploaded by

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

Unit-1 PHP

This document provides an introduction to PHP, detailing its features, history, and installation process. PHP is a server-side scripting language that is open-source and easy to learn, making it suitable for web development. The document also covers basic PHP syntax, data types, and how to embed PHP code within HTML.

Uploaded by

tasleembanu907
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/ 44

Unit- 1 INTRODUCTION TO PHP

Introduction to PHP:

o PHP stands for Hypertext Preprocessor.


o PHP is an interpreted language, i.e., there is no need for compilation.
o PHP is faster than other scripting languages, for example, ASP and JSP.
o PHP is a server-side scripting language, which is used to manage the
dynamic content of the website.
o PHP can be embedded into HTML.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

What is PHP?

PHP is an open-source, interpreted, and object-oriented scripting language that


can be executed at the server-side. PHP is well suited for web development.
Therefore, it is used to develop web applications (an application that executes
on the server and generates the dynamic page.).

Why we use PHP?

PHP is a server-side scripting language, which is used to design the dynamic


web applications with MySQL database.

o It handles dynamic content, database as well as session tracking for the


website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP,
IMAP, and many more.
o Using PHP language, you can control the user to access some pages of
your website.
o As PHP is easy to install and set up, this is the main reason why PHP is
the best language to learn.
o PHP can handle the forms, such as - collect the data from users using
forms, save it into the database, and return useful information to the
user. For example - Registration form.

History of PHP:

Rasmus Lerdorf—software engineer, Apache team member, is the creator of


PHP.

The first part of PHP was developed for his personal use in late 1994. This was
a CGI wrapper that helped him keep track of people who looked at his personal
site.

The next year, he put together a package called the Personal Home Page Tools
(a.k.a. the PHP Construction Kit) in response to demand from users.

Version 2 was soon released under the title PHP/FI and included the Form
Interpreter, a tool for parsing SQL queries.

By the middle of 1997, PHP was being used on approximately 50,000 sites
worldwide.
Zeev Suraski and Andi Gutmans, the two Israeli programmers who developed
the PHP3 and PHP4 parsers, have also generalized and extended their work
under the rubric of Zend.com.

The fourth quarter of 1998 initiated a period of explosive growth for PHP, as all
open source technologies enjoyed massive publicity.

In October 1998, according to the best guess, just over 100,000 unique domains
used PHP in some way. Just over a year later, PHP broke the one-million
domain mark.

Features of PHP:

PHP is very popular language because of its simplicity and open source. There
are some important features of PHP given below:

Performance:PHP script is executed much faster than those scripts which are
written in other languages such as JSP and ASP. PHP uses its own memory, so
the server workload and loading time is automatically reduced, which results in
faster processing speed and better performance.

Open Source:PHP source code and software are freely available on the web.
You can develop all the versions of PHP according to your requirement without
paying any cost. All its components are free to download and use.

Familiarity with syntax:PHP has easily understandable syntax. Programmers


are comfortable coding with it.

Embedded:PHP code can be easily embedded within HTML tags and script.
Platform Independent:PHP is available for WINDOWS, MAC, LINUX &
UNIX operating system. A PHP application developed in one OS can be easily
executed in other OS also.

Database Support:PHP supports all the leading databases such as MySQL,


SQLite, ODBC, etc.

Error Reporting -PHP has predefined error reporting constants to generate an


error notice or warning at runtime. E.g., E_ERROR, E_WARNING,
E_STRICT, E_PARSE.

Loosely Typed Language:PHP allows us to use a variable without declaring its


datatype. It will be taken automatically at the time of execution based on the
type of data it contains on its value.

Web servers Support:PHP is compatible with almost all local servers used
today like Apache, Netscape, Microsoft IIS, etc.

Security:PHP is a secure language to develop the website. It consists of


multiple layers of security to prevent threads and malicious attacks.

Installation & Configaration of PHP:

To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:

o WAMP for Windows


o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It
includes some other components too such as FileZilla, OpenSSL,
Webalizer, Mercury Mail, etc.

If you are on Windows and don't want Perl and other features of XAMPP, you
should go for WAMP. In a similar way, you may use LAMP for Linux and
MAMP for Macintosh.

How to install XAMPP server on windows

We will learn how to install the XAMPP server on windows platform step by
step. Follow the below steps and install the XAMPP server on your system.

Step 1: Click on the above link provided to download the XAMPP


server according to your window requirement.

Step 2: After downloading XAMPP, double click on the downloaded file and
allow XAMPP to make changes in your system. A window will pop-up, where
you have to click on the Next button.
Step 3: Here, select the components, which you want to install and click Next.

Step 4: Choose a folder where you want to install the XAMPP in your system
and click Next.
Step 5: Click Next and move ahead.

Step 6: XAMPP is ready to install, so click on the Next button and install the
XAMPP.

Step 7: A finish window will display after successful installation. Click on


the Finish button.
Step 8: Choose your preferred language.

Step 9: XAMPP is ready to use. Start the Apache server and MySQL and run
the php program on the localhost.

How to run PHP programs on XAMPP, see in the next tutorial.


Step 10: If no error is shown, then XAMPP is running successfully.

Embedding PHP code in your webpages:

If we want to use PHP in the Html document, then we have to follow the steps
which are given below. Using these simple steps, we can easily add the PHP
code.

Step 1: Firstly, we have to type the Html code in any text editor or open the
existing Html file in the text editor in which we want to use the PHP.

<!Doctype Html>
<Html>
<Head>
<Title>
Use a Php in Html
</Title>
</Head>
<Body>
</Body>
</Html>
Step 2: Now, we have to place the cursor in any tag of the <body> tag where
we want to add the code of PHP. And, then we have to type the start and end tag
of PHP.

<h1>
<?php ?>
</h1>

Step 3: After then, we have to type the code of PHP between the tags of PHP.

<h1>
<?php
echo "Hii User!! You are at JavaTpoint Site"
?>
</h1>

Step 4: When we successfully add the PHP code, then we have to save the Html
file and then run the file in the browser.

<!Doctype Html>
<Html>
<Head>
<Title>
Use a Php in Html
</Title>
</Head>
<Body>
<h1><?php echo "Hii User!! You are at JavaTpoint Site" ?></h1>
</Body>
</Html>
Understanding PHP:

A PHP script is executed on the server, and the plain HTML result is sent back
to the browser.

Basic PHP Syntax

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php

// PHP code goes here

?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:

ExampleGet your own PHP Server

A simple .php file with both HTML code and PHP code:

<!DOCTYPE html>

<html>

<body>

<h1>My first PHP page</h1>


<?php

echo "Hello World!";

?>

</body>

</html>

Note: PHP statements end with a semicolon (;).

PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-
defined functions are not case-sensitive.

In the example below, all three echo statements below are equal and legal:

Example

ECHO is the same as echo:

<!DOCTYPE html>

<html>

<body>

<?php

ECHO "Hello World!<br>";

echo "Hello World!<br>";

EcHo "Hello World!<br>";


?>

</body>

</html>

Note: However; all variable names are case-sensitive!

Look at the example below; only the first statement will display the value of
the $color variable! This is because $color, $COLOR, and $coLOR are treated
as three different variables:

Example

$COLOR is not same as $color:

<!DOCTYPE html>

<html>

<body>

<?php
$color = "red";

echo "My car is " . $color . "<br>";

echo "My house is " . $COLOR . "<br>";

echo "My boat is " . $coLOR . "<br>";

?>

</body>
</html>

PHP is whitespace insensitive

Whitespace is the stuff you type that is typically invisible on the screen,
including spaces, tabs, and carriage returns (end-of-line characters).

PHP whitespace insensitive means that it almost never matters how many
whitespace characters you have in a row.one whitespace character is the same as
many such characters.For example, each of the following PHP statements that
assigns the sum of 2 + 2 to the variable $four is equivalent −

$four = 2 + 2; // single spaces


$four <tab>=<tab2<tab>+<tab>2 ; // spaces and tabs
$four =
2+
2; // multiple lines

Comments in PHP:

A comment in PHP code is a line that is not executed as a part of the program.
Its only purpose is to be read by someone who is looking at the code.

Comments can be used to:

 Let others understand your code


 Remind yourself of what you did - Most programmers have experienced
coming back to their own work a year or two later and having to re-figure
out what they did. Comments can remind you of what you were thinking
when you wrote the code
 Leave out some parts of your code
PHP supports several ways of commenting:

Example

Syntax for comments in PHP code:

// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

Sending data to web browser:


With PHP, there are two basic ways to get output : echo and print

PHP echo and print Statements

echo and print are more or less the same. They are both used to output data to
the screen.

The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
(although such usage is rare) while print can take one argument. echo is
marginally faster than print.

The PHP echo Statement

The echo statement can be used with or without parentheses: echo or echo().
Display Text

The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):

Example

echo "<h2>PHP is Fun!</h2>";

echo "Hello world!<br>";


echo "I'm about to learn PHP!<br>";

echo "This ", "string ", "was ", "made ", "with multiple parameters.";

Display Variables

The following example shows how to output text and variables with
the echo statement:

Example

$txt1 = "Learn PHP";

$txt2 = "W3Schools.com";

$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";

echo "Study PHP at " . $txt2 . "<br>";


echo $x + $y;

Datatypes in php:

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

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 Data Types: Compound Types

It can hold multiple values. There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. resource
2. NULL

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:

<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>

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:

<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>

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:

<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

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:

<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>

Output:

Hello Javatpoint
Hello $company

PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.

Example:

<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and value
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>

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

You will learn more about array in later chapters of this tutorial.

PHP object

Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.

Example:

<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:

Bike Model: Royal Enfield

This is an advanced topic of PHP, which we will discuss later in detail.

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
$nl = NULL;
echo $nl; //it will not give any output
?>

Keywords in PHP:

PHP has a set of keywords that are reserved words which cannot be used as
function names, class names or method names. Prior to PHP 7, these keywords
could not be used as class property names either:

Keyword Description
abstract Declare a class as abstract

and A logical operator

as Used in the foreach loop

break Break out of loops and switch statements

callable A data type which can be executed as a function

case Used in the switch conditional

catch Used in the try..catch statement

class Declare a class

clone Create a copy of an object

const Define a class constant

continue Jump to the next iteration of a loop


declare Set directives for a block of code

default Used in the switch statement

do Create a do...while loop

echo Output text

else Used in conditional statements

elseif Used in conditional statements

empty Check if an expression is empty

enddeclare End a declare block

endfor End a for block

endforeach End a foreach block

endif End an if or elseif block


endswitch End a switch block

endwhile End a while block

extends Extends a class or interface

final Declare a class, property or method as final

finally Used in the try...catch statement

fn Declare an arrow function

for Create a for loop

foreach Create a foreach loop

function Create a function

global Import variables from the global scope

goto Jump to a line of code


if Create a conditional statement

implements Implement an interface

include Embed code from another file

include_once Embed code from another file

instanceof Test an object's class

insteadof Resolve conflicts with traits

interface Declare an interface

isset Check if a variable exists and is not null

list Assigns array elements into variables

namespace Declares a namespace

new Creates an object


or A logical operator

print Output text

private Declare a property, method or constant as private

protected Declare a property, method or constant as protected

public Declare a property, method or constant as public

require Embed code from another file

require_once Embed code from another file

return Exit a function and return a value

static Declare a property or method as static

switch Create a switch block

throw Throw an exception


trait Declare a trait

try Create a try...catch structure

unset Delete a variable or array element

use Use a namespace

var Declare a variable

while Create a while loop or end a do...while loop

xor A logical operator

yield Used in generator functions

yield from Used in generator functions

Variables in PHP:

In PHP, a variable is declared using a $ sign followed by the variable name.


Here, some important points to know about variables:
o As PHP is a loosely typed language, so we do not need to declare the data
types of the variables. It automatically analyzes the values and makes
conversions to its correct datatype.
o After declaring a variable, it can be reused throughout the code.
o Assignment Operator (=) is used to assign the value to a variable.

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;

Rules for declaring PHP variable:

o A variable must start with a dollar ($) sign, followed by the variable
name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated
as different variable.

PHP Variable: Declaring string, integer, and float

Let's see the example to store string, integer, and float values in PHP variables.

1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>

Output:

string is: hello string


integer is: 200
float is: 44.6

PHP Variable: Sum of two variables

1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>

Output:

11

PHP Variable: case sensitive

In PHP, variable names are case sensitive. So variable name "color" is different
from Color, COLOR, COLor etc.

1. <?php
2. $color="red";
3. echo "My car is " . $color . "<br>";
4. echo "My house is " . $COLOR . "<br>";
5. echo "My boat is " . $coLOR . "<br>";
6. ?>

Output:

My car is red
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is

PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

1. <?php
2. $a="hello";//letter (valid)
3. $_b="hello";//underscore (valid)
4.
5. echo "$a <br/> $_b";
6. ?>

Output:

hello
hello
1. <?php
2. $4c="hello";//number (invalid)
3. $*d="hello";//special symbol (invalid)
4.
5. echo "$4c <br/> $*d";
6. ?>

Output:

Parse error: syntax error, unexpected '4' (T_LNUMBER), expecting variable


(T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2

Constant in php:

A constant is an identifier (name) for a simple value. The value cannot be


changed during the script.

A valid constant name starts with a letter or underscore (no $ sign before the
constant name).

Note: Unlike variables, constants are automatically global across the entire
script.

PHP constants can be defined by 2 ways:


1. Using define() function
2. Using const keyword

Constants are similar to the variable except once they defined, they can never be
undefined or changed. They remain constant across the entire program. PHP
constants follow the same PHP variable rules. For example, it can be started
with a letter or underscore only.

Conventionally, PHP constants should be defined in uppercase letters.

PHP constant: define()

Use the define() function to create a constant. It defines constant at run time.
Let's see the syntax of define() function in PHP.

1. define(name, value, case-insensitive)


1. name: It specifies the constant name.
2. value: It specifies the constant value.
3. case-insensitive: Specifies whether a constant is case-insensitive. Default
value is false. It means it is case sensitive by default.

Let's see the example to define PHP constant using define().

File: constant1.php

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP");
3. echo MESSAGE;
4. ?>

Output:

Hello JavaTpoint PHP

Create a constant with case-insensitive name:

1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",true);//not case sensitive
3. echo MESSAGE, "</br>";
4. echo message;
5. ?>
Output:

Hello JavaTpoint PHP


Hello JavaTpoint PHP
1. <?php
2. define("MESSAGE","Hello JavaTpoint PHP",false);//case sensitive
3. echo MESSAGE;
4. echo message;
5. ?>

Output:

Hello JavaTpoint PHP


Notice: Use of undefined constant message - assumed 'message'
in C:\wamp\www\vconstant3.php on line 4
message

PHP constant: const keyword

PHP introduced a keyword const to create a constant. The const keyword


defines constants at compile time. It is a language construct, not a function. The
constant defined using const keyword are case-sensitive.

1. <?php
2. const MESSAGE="Hello const by JavaTpoint PHP";
3. echo MESSAGE;
4. ?>

Output:

Hello const by JavaTpoint PHP

Expression in php:

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

Example

<?php
$x=10;
$y=$x++; //equivalent to $y=$x followed by $x=$x+1
echo "x = $x y = $y";
?>

Output

x = 11 y = 10

Whereas following example uses prefix increment operator in assignment

Example

<?php
$x=10;
$y=++$x;; //equivalent to $x=$x+1 followed by $y=$x
echo "x = $x y = $y";
?>

Output
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:

pass

Operators in PHP:

PHP Operator is a symbol i.e used to perform operations on operands. In simple


words, operators are used to perform operations on variables or values. For
example:

1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and
$num is variable.

PHP Operators can be categorized in following forms:

ADVERTISEMENT
o Arithmetic Operators
o Assignment Operators
o Bitwise Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators

We can also categorize operators on behalf of operands. They can be


categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

Arithmetic Operators

The PHP arithmetic operators are used to perform common arithmetic


operations such as addition, subtraction, etc. with numeric values.

Operator Name Example Explanation

+ Addition $a + $b Sum of operands

- Subtraction $a - $b Difference of operands

* Multiplication $a * $b Product of operands

/ Division $a / $b Quotient of operands


% Modulus $a % $b Remainder of operands

** Exponentiation $a ** $b $a raised to the power $b

The exponentiation (**) operator has been introduced in PHP 5.6.

Assignment Operators

The assignment operators are used to assign value to different variables. The
basic assignment operator is "=".

Operator Name Example Explanation

= Assign $a = $b The value of right operand is assigned


to the left operand.

+= Add then Assign $a += $b Addition same as $a = $a + $b

-= Subtract then $a -= $b Subtraction same as $a = $a - $b


Assign

*= Multiply then $a *= $b Multiplication same as $a = $a * $b


Assign

/= Divide then $a /= $b Find quotient same as $a = $a / $b


Assign
(quotient)

%= Divide then $a %= $b Find remainder same as $a = $a % $b


Assign
(remainder)
Bitwise Operators

The bitwise operators are used to perform bit-level operations on operands.


These operators allow the evaluation and manipulation of specific bits within
the integer.

Operator Name Example Explanation

& And $a & $b Bits that are 1 in both $a and $b are set to
1, otherwise 0.

| Or (Inclusive $a | $b Bits that are 1 in either $a or $b are set to


or) 1

^ Xor (Exclusive $a ^ $b Bits that are 1 in either $a or $b are set to


or) 0.

~ Not ~$a Bits that are 1 set to 0 and bits that are 0
are set to 1

<< Shift left $a << $b Left shift the bits of operand $a $b steps

>> Shift right $a >> $b Right shift the bits of $a operand by $b


number of places

Comparison Operators

Comparison operators allow comparing two values, such as number or string.


Below the list of comparison operators are given:

Operator Name Example Explanation

== Equal $a == $b Return TRUE if $a is equal to $b


=== Identical $a === $b Return TRUE if $a is equal to $b, and
they are of same data type

!== Not identical $a !== $b Return TRUE if $a is not equal to $b,


and they are not of same data type

!= Not equal $a != $b Return TRUE if $a is not equal to $b

<> Not equal $a <> $b Return TRUE if $a is not equal to $b

< Less than $a < $b Return TRUE if $a is less than $b

> Greater than $a > $b Return TRUE if $a is greater than $b

<= Less than or $a <= $b Return TRUE if $a is less than or


equal to equal $b

>= Greater than or $a >= $b Return TRUE if $a is greater than or


equal to equal $b

<=> Spaceship $a <=>$b Return -1 if $a is less than $b


Return 0 if $a is equal $b
Return 1 if $a is greater than $b

ADVERTISEMENT

Incrementing/Decrementing Operators

The increment and decrement operators are used to increase and decrease the
value of a variable.

Operator Name Example Explanation


++ Increment ++$a Increment the value of $a by one, then return
$a

$a++ Return $a, then increment the value of $a by


one

-- decrement --$a Decrement the value of $a by one, then return


$a

$a-- Return $a, then decrement the value of $a by


one

Logical Operators

The logical operators are used to perform bit-level operations on operands.


These operators allow the evaluation and manipulation of specific bits within
the integer.

Operator Name Example Explanation

and And $a and $b Return TRUE if both $a and $b are true

Or Or $a or $b Return TRUE if either $a or $b is true

xor Xor $a xor $b Return TRUE if either $ or $b is true but not both

! Not ! $a Return TRUE if $a is not true

&& And $a && $b Return TRUE if either $a and $b are true

|| Or $a || $b Return TRUE if either $a or $b is true


String Operators

The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:

Operator Name Example Explanation

. Concatenation $a . $b Concatenate both $a and $b

.= Concatenation and $a .= $b First concatenate $a and $b, then


Assignment assign the concatenated string to
$a, e.g. $a = $a . $b

Array Operators

The array operators are used in case of array. Basically, these operators are used
to compare the values of arrays.

Operator Name Example Explanation

+ Union $a + $y Union of $a and $b

== Equality $a == $b Return TRUE if $a and $b have same


key/value pair

!= Inequality $a != $b Return TRUE if $a is not equal to $b

=== Identity $a === $b Return TRUE if $a and $b have same


key/value pair of same type in same order

!== Non- $a !== $b Return TRUE if $a is not identical to $b


Identity
<> Inequality $a <> $b Return TRUE if $a is not equal to $b

Type Operators

The type operator instanceof is used to determine whether an object, its parent
and its derived class are the same type or not. Basically, this operator
determines which certain class the object belongs to. It is used in object-
oriented programming.

1. <?php
2. //class declaration
3. class Developer
4. {}
5. class Programmer
6. {}
7. //creating an object of type Developer
8. $charu = new Developer();
9.
10. //testing the type of object
11. if( $charu instanceof Developer)
12. {
13. echo "Charu is a developer.";
14. }
15. else
16. {
17. echo "Charu is a programmer.";
18. }
19. echo "</br>";
20. var_dump($charu instanceof Developer); //It will return true.
21. var_dump($charu instanceof Programmer); //It will return false.
22.?>

Output:

Charu is a developer.
bool(true) bool(false)
Execution Operators

PHP has an execution operator backticks (``). PHP executes the content of
backticks as a shell command. Execution operator and shell_exec() give the
same result.

Operator Name Example Explanation

`` backticks echo `dir`; Execute the shell command and return the
result.
Here, it will show the directories available in
current folder.

Error Control Operators

PHP has one error control operator, i.e., at (@) symbol. Whenever it is used
with an expression, any error message will be ignored that might be generated
by that expression.

Operator Name Example Explanation

@ at @file ('non_existent_file') Intentional file error

PHP Operators Precedence

Let's see the precedence of PHP operators with associativity.

Associativity

Operators Additional Information


clone new clone and new non-
associative

[ array() left

** arithmetic right

++ -- ~ (int) (float) (string) (array) increment/decrement and right


(object) (bool) @ types

instanceof types non-


associative

! logical (negation) right

*/% arithmetic left

+-. arithmetic and string left


concatenation

<< >> bitwise (shift) left

< <= > >= comparison non-


associative

== != === !== <> comparison non-


associative

& bitwise AND left

^ bitwise XOR left

| bitwise OR left
&& logical AND left

|| logical OR left

?: ternary left

= += -= *= **= /= .= %= &= |= ^= assignment right


<<= >>= =>

and logical left

xor logical left

or logical left

, many uses (comma) left

You might also like