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

PHP Unit I

Uploaded by

Chandana Gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

PHP Unit I

Uploaded by

Chandana Gouda
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

BCA VI SEM PHP Unit I

Internet: The internet, sometimes simply called the net, is a worldwide


system of interconnected computer networks and electronic devices that
communicate with each other using an established set of protocols.

WWW: WWW stands for World Wide Web and is commonly known as the Web.
The WWW was started by CERN in 1989. WWW is defined as the collection of
different websites around the world, containing different information shared via
local servers.

Web pages are linked together using hyperlinks which are HTML-formatted and,
also referred to as hypertext, these are the fundamental units of the Internet and
are accessed through Hypertext Transfer Protocol(HTTP).

Website: A site or website is a central location of various web pages that are all
related and can be accessed by visiting the home page of the website using a
browser.

webpage: It is a hypertext document connected to the World WideWeb

 Types of web pages


1. Static Web Pages – Does not contain logic
2. Dynamic Web Pages - Contains logic

Application: Application (app for short) is software designed to perform a


group of coordinated functions, tasks, or activities for the benefit of the user.

We ca n develop three types of applications.

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

1. Windows based applications

2. Web ba s e d applications

3. Mobile applications

Web server: Web Server: Web server is a program which processes the network
requests of the users and serves them with files that create web pages. This
exchange takes place using Hypertext Transfer Protocol (HTTP).
Basically, web servers are computers used to store HTTP files which makes a
website and when a client requests a certain website, it delivers the requested
website to the client. For example, you want to open Facebook on your laptop
and enter the URL in the search bar of google. Now, the laptop will send an HTTP
request to view the facebook webpage to another computer known as the
webserver. This computer (webserver) contains all the files (usually in HTTP
format) which make up the website like text, images, gif files, etc. After
processing the request, the webserver will send the requested website-related
files to your computer and then you can reach the website.

INTRODUCTION TO PHP
PHP is server-side scripting language implemented by Rasmus Lerdorf in
1994 using C and PERL languages. He implemented PHP 1.0 totrack total
number of visitors in his server. PHP stands for Personal Home Page. It
also has an alias name Hypertext Preprocessor.
What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely used, open-source scripting language
 PHP scripts are executed on the server

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

 PHP is free to download and use.


What is a PHP File?
 PHP files can contain text, HTML, CSS, JavaScript, and PHPcode
 PHP codes are executed on the server, and the result is returnedto the
browser as plain HTML
 PHP files have extension ".php"
What Can PHP Do?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on theserver
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data
Why PHP?
 PHP runs on various platforms (Windows, Linux, Unix, Mac OSX, etc.)
 PHP is compatible with almost all servers used today (Apache,IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource:
www.php.net
 PHP is easy to learn and runs efficiently on the server side
 This language is very simple to learn and runs efficiently on theserver
side.
 It supports many databases such as MySQL, Oracle, PostgreSQLetc.
 It is perfectly suited for Web development and can be embeddeddirectly
into the HTML code.
 PHP can also be used to create dynamic web pages.
Features of PHP: The main features of php is; it is a server side open source
scripting Or language so you can free download this and use It is most popular
and frequently used worldwide scripting language, the main reason of
popularity is; It is open source and very simple.
 Simple: It is very simple and easy to use, compare to other scripting
language, this is widely used all over the world

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

 Faster: It is faster than other scripting language e.g. asp and jsp.
 Interpreted: It is an interpreted language, i.e. there is no need for
compilation.
 Open Source: Open source means you no need to pay for use php, you
can free download and use.
 Case Sensitive: PHP is case sensitive scripting language at time of
variable declaration. In PHP, all keywords (e.g. if, else, while, echo,
etc.), classes, functions, and user-defined functions are NOT case-
sensitive
 Simplicity: PHP provides a lot of pre-define functions to secure your
data. It is also compatible with many third-party applications, and PHP
can easily integrate with other.In PHP script there is no need to include
libraries like c, special compilation directives like Java, PHP engine
starts execution from (<?) escape sequence and end with a closing
escape sequence (<?). In PHP script, there is no need to write main
function. And also you can work with PHP without creating a class.
 Efficiency: PHP 4.0 introduced resource allocation mechanisms and
more pronounced support for object-oriented programming, in
addition to session management features. Eliminating unnecessary
memory allocation.
 Platform Independent: PHP code will be run on every platform,
Linux, Unix, Mac OS X, Windows.
 Cross Database: It is integrated with a number of
popular databases, including MySQL, Oracle, Sybase, Informix,
and Microsoft SQL Server.
 Security: It supports different types of security functionalities to apply
security to applications like one-way encryption, two-way encryption,
authentication etc.
 Flexibility: You can say that PHP is a very flexible language because
of PHP is an embedded language you can embed PHP scripts with
HTML, JAVA SCRIPT, WML, XML, and many others. You can run your
PHP script any device like mobile Phone, tabs, laptops, PC and other
because of PHP script execute on the server then after sending to the

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

browser of your device.


 Familiarity: If you are in programming background then you can
easily understand the PHP syntax. And you can write PHP script
because of most of PHP syntax inherited from other languages like C
or Pascal.
 Error Reporting: PHP have some predefined error reporting
constants to generate a warning or error notice.
 Loosely Typed Language: PHP supports variable usage without
declaring its data type. It will be taken at the time of the execution based
on the type of data it has on its value.
 Protocol Independent: PHP supports a large number of major
protocols such as POP3, IMAP, and LDAP.PHP4 added support for Java
and distributed object architectures (COM and CORBA), making n-tier
development a possibility for the first time.
 Cross Web Server: It supports many web servers like IIS, Apache,
Tomcat, etc.
 Editor independent: It supports different types of editors to develop
programs or applications. We can also use light weight editors like
Notepad, Edit+, etc.
COMMON USES OF PHP
 It is used to create dynamic websites.
 To Interacting with web server (Apache etc)
 To interacting with any back end / database server e.g. MySQL
 To implement the business logical layers (one or more)
 Access Cookies variable and set cookies
 Using php you can restrict user to access specific web page
 PHP usually used to output HTML code to the browser
 It is used for send and receive E-Mails.
 You can use PHP to find today's date, and then build a calendar forthe
month.
 Using php you can count your visitors on your website.
 You can use PHP to create a special area of your website for members.

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

 Using php you can create login page for your user.
 Using php you can add, delete, modify elements within
yourdatabase thru PHP.
 Using PHP, you can restrict users to access some pages of your
website.
 It can encrypt data.
 PHP performs system functions, i.e. from files on a system it can
create, open, read, write, and close them.
 It can handle forms, i.e. gather data from files, save data to a file.

"Hello World" Script in PHP


To get a feel for PHP, first start with simple PHP scripts. Since "Hello, World!"
is an essential example, first we will create a friendly little "Hello, World!"
script.
<html>
<head>
<title>Hello World</title>
</head>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
–Hello, World!
All PHP code must be included inside one of the three special markup tags, are
recognized by the PHP Parser.
<?php PHP code goes here ?>
<? PHP code goes here ?>
<% PHP code goes here %>
<script language = "php"> PHP code goes here </script>
A most common tag is the <?php...?> .

PHP is case sensitive: PHP is a case sensitive language.


Try out following example
<?php
$capital = 67;

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

print("Variable capital is $capital<br>");

print("Variable CaPiTaL is $CaPiTaL<br>");


?>
Output:
Variable capital is 67Variable CaPiTaL is
IMPORTANT POINTS:
1. Every statement in PHP should be terminated by ‘;’.
2. PHP file extension should be .php.
3. PHP script should place within the script declaration tags.
<?php
………
………
?

SOFTWARES REQUIRED FOR TO WORK WITH PHP:


1. Browser - Internet Explorer
2. Server - Apache
3. Server-side script - PHP
4. Database - MYSQL
TOOLS TO WORK WITH PHP:
1. XAMPP - Cross Apache MYSQL PHP Perl
2. WAMPP - Window Apache MYSQL PHP Perl
3. LAMPP - Linux Apache MYSQL PHP Perl
4. MAMPP - Macintosh Apache MYSQL PHP Perl

HOW TO DOWNLOAD & INSTALL XAMPP TOOL?


1. Go to Google
2. XAMPP download in Google Search
3. Select appropriate version of XAMPP based on OS
4. Click on download

INSTALLATION
1. Double click on downloaded file
2. Click on the Next button

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

3. Select drive where you want to installed


4. Click on the Next button until you will get finished button
5. Click on Finish button

HOW TO WRITE PHP PROGRAM


1. Open ant Editor
2. Create a new file
3. Save the file name with extension .php inside “htdocs” folder
C:/XAMPP/htdocs (Ex: abc.php)
4. We need to write PHP code inside saved fileEx:
<?php
……..
……..
?>
5. Save again php file

HOW TO EXECUTE PHP PROGRAM


1. Open any browser
2. Type in the url http://localhost/program.php name and pressenter
3. You can see now output if we don’t have any error
Example:
1. Open notepad or any editor and implement PHP script.
<?php
print “WELCOME”;print “<br>”;
$x=100;
print $x;
?>
2. Save this file in htdocs folder with .php extension.
3. To display output, open browser and enter URL address
byproviding site name with server name.

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

TYPES OF ERRORS: Mistake or fault occurs in a program is callederror.


There are basically 4 types of errors in PHP:
1. Notice
2. Warning
3. Fatal Error
4. Parse Error
NOTICE:
Notice that an error is the same as a warning error i.e. in the notice error
does not stop execution of the script. Notice that the error occurs when
you try to access the undefined variable, and then produce a notice
error.
Example
<?php
$a="Uday";
echo "Notice Error !!";

echo $b;
?>
Output: In the above code we defined a variable which named $a. But we call
another variable i.e. $b, which is not defined. So there will be a notice error
produced but execution of the script does not stop, you will see a message Notice
Error! Like in the followingimage:

WARNING:
Warning errors will not stop execution of the script. The main reason for
warning errors are to include a missing file or using the incorrect number of
Prof. Vittal Tubachi
9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

parameters in a function.
Example
<?php
echo "Warning Error!!"; include ("Welcome.php");
?>
Output: In the above code we include a welcome.php file, however the
welcome.php file does not exist in the directory. So there will bea warning
error produced but that does not stop the execution of the script i.e. you will
see a message Warning Error !!.

FATAL ERROR:
Fatal errors are caused when PHP understands what you've written;
however what you're asking it to do can't be done. Fatal errors stop the
execution of the script. If you are trying to access the undefined
functions, then the output is a fatal error.
Example
<?php
function fun1()
{
echo "Uday Kumar";
}
fun2();
echo "Fatal Error !!";
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Output: In the above code we defined a function fun1 but we call another
function fun2 i.e. func2 is not defined. So a fatal error will be produced that
stops the execution of the script. Like as in the following image.

PARSE ERROR:
The parse error occurs if there is a syntax mistake in the script; the output
is Parse errors. A parse error stops the execution of the script. There are
many reasons for the occurrenceof parse errors in PHP. The common reasons
for parse errors are as follows:
Common reason of syntax errors are:
a. Unclosed quotes
b. Missing or Extra parentheses
c. Unclosed braces
d. Missing semicolon
Example
<?php
echo "C#"; echo "PHP"echo "C";
?>
Output: In the above code we missed the semicolon in the second line. When
that happens there will be a parse or syntax error which stops execution of
the script, as in the following image:

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

OUTPUT FUNCTIONS IN PHP:


1. echo statement
 In PHP ‘echo’ statement is a language construct and not a function, so it
can be used without parenthesis.
 But we are allowed to use parenthesis with echo statement whenwe
are using more than one argument with it.
 The end of echo statement is identified by the semi-colon (‘;’). Wecan
use ‘echo’ to output strings or variables.
 Displaying Strings: The keyword echo followed by the string to be
displayed within quotes.
<?php
echo "Hello,This is a display string example!";
?>
Output: Hello,This is a display string example!
 Displaying Strings as multiple arguments: We can pass multiple string
arguments to the echo statement instead of single string argument, separating
them by comma (‘,’) operator. For example, ifwe have two strings say “Hello”
and “World” then we can pass them as (“Hello”,”World”).
<?php
echo "Multiple ","argument ","string!";
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Output: Multiple argument string!


 Displaying Variables: Displaying variables with echo statement isalso
as easy as displaying normal strings.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20;

echo $text."\n";
echo $num1."+".$num2."=";echo $num1 + $num2;
?>
Output: Hello, World!
10+20=30
The (.) operator in the above code can be used to concatenate two strings in
PHP and the “\n” is used for a new line and is also known as line-break.
print statement
 The PHP print statement is similar to the echo statement and can be
used alternative to echo at many times.
 It is also language construct and so we may not use parenthesis: print
or print ().
 The main difference between the print and echo statement is that print
statement can have only one argument at a time and thus can print a
single string. Also, print statement always returns a value 1.
 Like echo, print statement can also be used to print strings and
variables.
 Displaying String of Text: We can display strings with print statement
in the same way we did with echo statements. The only difference is we
can not display multiple strings separated by comma(,) with a single
print statement. Below example shows how to display strings with the
help of PHP print statement:-
<?php
print "Hello, world!";
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Output: Hello, world!


 Displaying Variables: Displaying variables with print statement isalso
same as that of echo statement.
<?php
$text = "Hello, World!";
$num1 = 10;
$num2 = 20; print $text."\n";

print $num1."+".$num2."=";print $num1 + $num2;


?>
Output: Hello, World!
10+20=30

Difference between Echo and Print in PHP


Echo Statement Print Statement
In Echo, we can pass multiple arguments In Print, we cannot pass
separated by commas. multiple arguments.
In Echo, we can exhibit the outputs of Through the Print statement,
one or more strings separated by we can only show the strings.
commas.
Echo can be used with or without Print can also be used with or
parentheses without parentheses.
It never returns any value. It always returns the integer
value that is 1.
This statement is fast as compared to the It is slow as compared to the
print statement. echo statement.

VARIABLES:
 Variable is an identifier which holds data or another one variable and
whose value can be changed at the execution time of script.

 Syntax: $variablename=value;

 A variable starts with the $ sign, followed by the name of thevariable


 A variable name must start with a letter or the
underscorecharacter
 A variable name can't start with a number.
 A variable name can only contain alpha-numeric characters and

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

underscores (A-z, 0-9 and _)


 Variable names are case-sensitive ($str and $STR both are two
different)
Example:
<?php
$str="Hello world!";
$a=5;
$b=10.5;
echo "String is: $str <br/>";echo "Integer is: $x <br/>"; echo "Float is: $y
<br/>";
?>

VARIABLE SCOPES
 Scope of a variable is defined as its extent in program within whichit
can be accessed, i.e. the scope of a variable is the portion of the program with
in which it is visible or can be accessed.
 Depending on the scopes, PHP has three variable scopes:

1. Local variables: The variables declared within a function are called local
variables to that function and has its scope only in that particular function. In
simple words it cannot be accessed outside that function. Any declaration of
a variable outside the function with same name as that of the one within
the function is a complete different variable.
Example:
<?php
$num = 60; function local_var()
{
$num = 50;
echo "local num = $num \n";
}
local_var();
echo "Variable num outside local_var() is $num \n";
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Output: local num = 50


Variable num outside local_var() is 60
2. Global variables: 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:
<?php
$num = 20;

function global_var()
{
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 variable: It is the characteristic of PHP to delete the variable,
ones 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 static keyword, and the variables are then called as static
variables.
Example:
<?php
function static_var()
{
static $num = 5;
$sum = 2;
$sum++;

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

$num++;
echo $num "\n";echo $sum "\n";
}
static_var();

static_var();
?>
Output: 6 3
7 3
Example:
<?php
function myTest()
{
static $x = 0;echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Output: 0 1 2

CONSTANTS:
 Constants are name or identifier that can't be changed during the
execution of the script. In php constants are define in two ways.
1. Using define() function
2. Using const keyword
 In php declare constants follow same rule variable declaration.
Constant start with letter or underscore only
 Create a PHP Constant
Create constant in php by using define () function.
Syntax: define((name, value, case-insensitive)

Name: Specifies the name of the constant

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Value: Specifies the value of the constant


Case-insensitive: Specifies whether the constant name should be case-
insensitive. Default is false
Example:
<?php
define("MSG","Hello world!");//using case-sensitiveecho MSG;
?>
Output: Hello world!
Example:
<?php
define("MSG","Hello world!");//using case-insensitiveecho msg;
?>
Output: Hello world!
 Define constant using cons keyword in PHP
The const keyword defines constants at compile time. It is a language
construct not a function. It is bit faster than define(). It is always case
sensitive.
Example:
<?php
const MSG="Hello world!";echo MSG;
?>

DATATYPES

PHP data types are used to hold different types of data or values. PHP
supports the following data types: String, Integer, Float, Boolean, Array,
Object, NULL, and Resource.
Integer:
 Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point.
 They can be decimal (base 10), octal (base 8) or hexadecimal (base
16).
 The default base is decimal (base 10).
 The octal integers can be declared with leading 0 and
Prof. Vittal Tubachi
9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

thehexadecimal can be declared with leading 0x.


 The range of integers must lie between -2^31 to 2^31.

Example:
<?php
// decimal base integers
$deci1 = 50;
$deci2 = 654;
$sum = $deci1 + $deci2;echo $sum;
?>
Output: 704

Float(or)double:
 It can hold numbers containing fractional or decimal part including
positive and negative numbers.
 By default, the variables add a minimum number of decimalplaces.

Example:

<?php
$val1 = 50.85;
$val2 = 654.26;
$sum = $val1 + $val2;echo $sum;
?>
Output: 705.11

String:
 It can hold letters or any alphabets, even numbers are included.
 These are written within double quotes during declaration.
 The strings can also be written within single quotes, but it will be
treated differently while printing variables.
Example:
<?php
$name = "Krishna";
echo "The name of the Geek is $name \n";echo 'The name of the geek is

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

$name';
?>
Output: The name of the Geek is Krishna The name of the geek is
$name

NULL:
 These are special types of variables that can hold only one valuei.e.,
NULL.
 We follow the convention of writing it in capital form, but its case
sensitive.

Example:
<?php
$nm = NULL;
echo $nm; // This will give no output
?>

Boolean:
 Hold only two values, either TRUE or FALSE.
 Successful events will return true and unsuccessful events return
false.
 NULL type values are also treated as false in Boolean.
 If a string is empty then it is also considered as false in booleandata
type.
Example:
<?php
if(TRUE)
echo "This condition is TRUE";if(FALSE)
echo "This condition is not TRUE";
?>
Output: This condition is TRUE
This condition is not TRUE

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

Arrays:
 Array is a compound data-type which can store multiple values ofsame
data type.
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0]\n"; echo "Second Element: $intArray[1]\n";
echo "Third Element: $intArray[2]\n";

?>
Output: First Element: 10
Second Element: 20
Third Element: 30

Objects:
 Objects are defined as instances of user defined classes that can
hold both values and functions.
Resources:
 Resources in PHP are not an exact data type. These are basically used
to store references to some function call or to external PHP resources. For
example, consider a database call. This is an external resource.
COMMENTING PHP CODE:
 A comment is the portion of a program that exists only for the human
reader and stripped out before displaying the programs result. There are two
commenting formats in PHP −
1. Single-line comments − They are generally used for short explanations
or notes relevant to the local code. Here are the examples of single line
comments.
<?php
# This is a comment, and
# This is the second line of the comment
// This is a comment too. Each style comments onlyprint "An example with
single line comments";
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

2. Multi-lines comments −They are generally used to provide pseudo


code algorithms and more detailed explanations when necessary. This style
of commenting is the same as in C.
<?php
/* This is a comment with multilineSubject: PHP
*/
print "An example with multi line comments";
?>
PHP Operators: Operators are used to perform operations on variables and
values. PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
PHP Arithmetic Operators: The arithmetic operators are used to perform common
arithmetical operations, such as addition, subtraction, multiplication etc. Here's a
complete list of PHP's arithmetic operators:
Operator Example Result

+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y.


* Multiplicatio $x * $y Product of $x and $y.
n
/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided


by $y

<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14

echo($x - $y); // 0utputs: 6

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

echo($x * $y); // 0utputs: 40

echo($x / $y); // 0utputs: 2.5

echo($x % $y); // 0utputs: 2


?>
PHP Assignment Operators: The assignment operators are used toassign
values to variables.
Operator Description Example Is The Same
As
= Assign $x = $y $x = $y

+= Add and assign $x += $y $x = $x + $y

-= Subtract and assign $x -= $y $x = $x - $y

*= Multiply and assign $x *= $y $x = $x * $y

/= Divide and assign $x /= $y $x = $x / $y


quotient
%= Divide and assign $x %= $y $x = $x % $y
modulus

<?php
$x = 10;
echo $x; // Outputs: 10
$x = 20;
$x += 30;
echo $x; // Outputs: 50
$x = 50;
$x -= 20;
echo $x; // Outputs: 30
$x = 5;
$x *= 25;
echo $x; // Outputs: 125
$x = 50;
$x /= 10;
echo $x; // Outputs: 5
$x = 100;

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

$x %= 15;
echo $x; // Outputs: 10
?>
PHP Comparison Operators: The comparison operators are used tocompare
two values in a Boolean fashion.
Operator Name Example Result
== Equal $x == $y True if $x is equal to $y

=== Identical $x === $y True if $x is equal to $y, and


they are of the same type
!= Not equal $x != $y True if $x is not equal to $y

<> Not equal $x <> $y True if $x is not equal to $y

!== Not identical $x !== $y True if $x is not equal to $y, or


they are not of the same type

< Less than $x < $y True if $x is less than $y

> Greater than $x > $y True if $x is greater than $y

<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true

var_dump($x === $z); // Outputs: boolean false

var_dump($x != $y); // Outputs: boolean true

var_dump($x !== $z); // Outputs: boolean true

var_dump($x < $y); // Outputs: boolean true

var_dump($x > $y); // Outputs: boolean false

var_dump($x <= $y); // Outputs: boolean true

var_dump($x >= $y); // Outputs: boolean false

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

?>

PHP Incrementing and Decrementing Operators

Operator Name Syntax Operation


++ Pre-Increment ++$x First increments $x by one, then return
$x
— Pre-Decrement –$x First decrements $x by one, then return
$x
++ Post-Increment $x++ First returns $x, then increment it by
one
— Post- $x– First returns $x, then decrement it by
Decrement one

<?php
$x = 10;
echo ++$x; // Outputs: 11echo $x; // Outputs: 11
$x = 10;
echo $x++; // Outputs: 10echo $x; // Outputs: 11
$x = 10;
echo --$x; // Outputs: 9echo $x; // Outputs: 9
$x = 10;
echo $x--; // Outputs: 10echo $x; // Outputs: 9
?>

PHP Logical 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
and Logical $x and True if both the operands are true else
AND $y false
or Logical $x or $y True if either of the operands is true else
OR false

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

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


XOR $y false if both are true
&& Logical $x && True if both the operands are true else
AND $y false
|| Logical $x || $y True if either of the operands is true else
OR false
! Logical !$x True if $x is false
NOT

<?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";
?>
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 $x.=$y First concatenates then

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi


BCA VI SEM PHP Unit I

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

<?php
$x = "Geeks";
$y = "for";
$z = "Geeks!!!";
echo $x . $y . $z, "\n";
$x .= $y . $z;
echo $x;
?>

Ternary operator: The ternary operator (?:) is a conditional operator used to


perform a simple comparison or check on a condition having simple statements.
It decreases the length of the code performing conditional operations. The order
of operation of this operator is from left to right. It is called a ternary operator
because it takes three operands- a condition, a result statement for true, and a
result statement for false. The syntax for the ternary operator is as follows.
Syntax:
(Condition) ? (Statement1) : (Statement2);
 Condition: It is the expression to be evaluated and returns a boolean
value.
 Statement 1: It is the statement to be executed if the condition results in a
true state.
 Statement 2: It is the statement to be executed if the condition results in a
false state.
<?php
$a = 10;
$b = $a > 15 ? 20 : 5;
print ("Value of b is " . $b);
?>

Prof. Vittal Tubachi


9538626511

BLDEA’s BCA College Jamkhandi

You might also like