0% found this document useful (0 votes)
5 views70 pages

Unit 3

This document provides an overview of server-side and client-side scripting, focusing on PHP as a server-side language. It explains the architecture, features, and differences between server-side and client-side scripting, as well as the basics of PHP syntax, variables, and arrays. Additionally, it highlights the advantages of using PHP for web development and its compatibility with various platforms and databases.

Uploaded by

ashamnoorphotos
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)
5 views70 pages

Unit 3

This document provides an overview of server-side and client-side scripting, focusing on PHP as a server-side language. It explains the architecture, features, and differences between server-side and client-side scripting, as well as the basics of PHP syntax, variables, and arrays. Additionally, it highlights the advantages of using PHP for web development and its compatibility with various platforms and databases.

Uploaded by

ashamnoorphotos
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/ 70

WebTechnology

CIE -356T

UNIT III

Department of CSE.BVCOE
Introduction to Server-Side
Development with PHP

Department of CSE.BVCOE
Server-Side Development with PHP
✓It is the technology which is used in the web development which involves in employing the
scripts on a web server which produce a response customized for each user’s request to
the website.
✓It is related to client server architecture where a client request the server to begin
communication or initiate the communications.
✓ The server having the scripting the help or response to client corresponding to their
request.
✓Server-side scripting: is a programming technique for creating code that may run software
on the server side.
✓In other words, server-side scripting is any scripting method that may operate on a web
server.
✓At the server end, actions such as website customization, dynamic changes in website
content, response creation to user requests, database access, and many more are carried
out.
✓Server-side scripting creates a communication channel between a server and a client.
✓Previously, CGI (Common Gateway Interface) scripts were used to implement server-side
scripting, and CGI was created to execute scripts written in computer languages such as
C++ or Perl on websites. Department of CSE.BVCOE
Server-Side Development with PHP

✓The server-side is made up of three parts:


1. the database
2. the server
3. the APIs, and the backend web software written in the server-side
scripting language.
When a browser requests a page with server-side scripting, the web server
evaluates the script before delivering the page to the browser.
✓ In this case, script processing may entail collecting information from a
database, performing simple computations, or selecting the relevant material
to be shown on the client end.
✓The output is provided to the web browser when the script is processed. The
web server hides the scripts from the end user until the content is delivered,
making the data and source code safer.
Department of CSE.BVCOE
Server-Side Scripting languages are:
• There are various server-side scripting languages. Some main server-side scripting
languages are as follows:
Python
✓It is an open-source language that is very powerful and easy to learn. It is suitable
for beginners because it is simple to learn and read.
✓It is believed to be used by Google and YouTube. It is a OOPs language with
dynamic typing and data structures.
✓ It has grown to be one of the most popular languages for both quick application
development and web development.
PHP
✓It is an open-source server-side scripting programming language mainly designed
for web apps and is the most utilized scripting language.
✓It allows you to retrieve and manipulate data from a database and is utilized along
with SQL to query the database.
✓ It is a fast and simple language to learn and develop, and Facebook, Wikipedia,
and WordPress utilize it.
Department of CSE.BVCOE
Server-Side Scripting languages are:
Ruby
✓It is a free and open-source programming language that was developed and firstly
introduced in the early 1990s.
✓It is a dynamic language that is simple to read and write and an OOPs language that
is interpreted as it runs.
✓It has evolved continuously since its development and is one of the most utilized
web development languages.
Features of Server-side Scripting
There are various features of server-side scripting. Some main features of the
server-side scripting are as follows:
✓It is connected with data access, error handling, and data processing speed.
✓It is processed and interacts with the server.
✓Using a highly integrated programming language makes it more secure than client-
side scripting.
Department of CSE.BVCOE
Client Side Scripting languages are:
✓Client-side scripting generates code that may be executed on the client end
without needing server-side processing.
✓These scripts are typically embedded into HTML text. Client-side scripting may be
utilized to check the user's form for problems before submitting it and to change
the content based on the user input.
The web needs three components to function:
1. Client
2. Database
3. Server.
• The client-side scripting may significantly reduce server demand. It is intended to
be utilized as a scripting language with a web browser as the host program.
• The HTML and CSS are delivered as plain text when a user uses a browser to
request a webpage from the server, and the browser understands and renders the
web content at the client end.
Department of CSE.BVCOE
Client Side Scripting languages are:
Client-side Scripting Languages
✓ There are various client-side scripting languages. Some main client-side scripting languages are as follows:
HTML
CSS
✓ CSS is an abbreviation for Cascading Style Sheets. It provides a technique for creating graphic elements that help a web
application's appearance look more appealing.
✓ A style tag in a web page defines all the specifics regarding the web page's presentation, including its border styles,
image styles, colour, font styles, borders, format, font size, margins, padding, etc.
JavaScript
• It is a client-side scripting language designed for a specific purpose, but several JavaScript frameworks are already
Features of Client-side Scripting
• There are various features of client-side scripting. Some main features of the client-side scripting are as follows:
• It is intended to execute code on which a web browser runs, and the results of the inputs are delivered to an accessible
user.
• Client-side scripting enables greater involvement with clients via the browser and is used to validate programs and
functionality based on the request.
• The client does not include any contact with the server in client-side scripting; the only interaction is receiving the
requested data.
✓ utilized as server-side scripting technology.

Department of CSE.BVCOE
Client Side Scripting languages are:
VBScript
✓VBScript is based on Visual Basic, which was created by Microsoft in 1996. It
is a scripting programming language that is lightweight, fast, and easy to
learn. It is not a OOPs language but is similar to JavaScript.
Features of Client-side Scripting
There are various features of client-side scripting. Some main features of the
client-side scripting are as follows:
✓It is intended to execute code on which a web browser runs, and the results
of the inputs are delivered to an accessible user.
✓Client-side scripting enables greater involvement with clients via the browser
and is used to validate programs and functionality based on the request.
✓The client does not include any contact with the server in client-side
scripting; the only interaction is receiving the requested data.
Department of CSE.BVCOE
Difference between server side scripting and Client Side Scripting are:

Features Server side scripting Client Side Scripting

Uses Server-side scripting is utilized in the backend and Client-side scripting is utilized at the front end,
the source code is invisible or hidden from the which users may access via the browser.
client side as it is processed on the server side.
Primary Function User through the web browser can access the All the codes are on the browser.
client request from the server.

Primary Function The main function of this scripting is to The main purpose of this scripting is to give the
manipulate and grant access to the requested requested output to the end-user.
database.
Processing It needs server interaction. It doesn't need any server interaction.

Security It is more secure while working on a web app. It is less secure than server-side scripting due to
the code accessibility offered to the client.

Department of CSE.BVCOE
Difference between server side scripting and Client Side Scripting are:

Features Server side scripting Client Side Scripting

Running It executes on the web server. It executes on the remote computer system.

Dependability It doesn't depend on the client. It depends on the user's browser version.

File Access It offers complete access to the file that is stored in It doesn't offer any access to the files on the web
the web database server. servers.

Code Allowance It enables the backend developer to hide the The user is given access to the written code after
source code from the user. confirming their requirements.

Occurrence It only responds after the user begins the browsing It happens when the browser processes all of the
request. codes and then acts according to the client's
needs.
Department of CSE.BVCOE
Difference between server side scripting and Client Side Scripting are:

Features Server side scripting Client Side Scripting

Affect It may reduce the server load. It may effectively customize web pages and offer
dynamic websites.

Languages The server-side scripting programming languages, Its programming languages are HTML, CSS, and
Involved such as It, ColdFusion, Python, ASP.net, Java, C++, JavaScript.
Ruby, C#, etc.
Response Slow Fast

Department of CSE.BVCOE
What is PHP?

✓It is an acronym for "It: Hypertext Preprocessor"


✓It is a widely-used, open source scripting language
✓It scripts are executed on the server
✓It is free to download and use
✓It is also object oriented language if you know the concept of c, c++, Java then you can easily
learn and use PHP.
What Can It Do?
✓It can generate dynamic page content
✓it can create, open, read, write, delete, and close files on the server
✓It can collect form data
✓It can send and receive cookies
✓It can add, delete, modify data in your database
✓It can be used to control user-access
✓It can encrypt data
✓With It we are not limited to output HTML. we can output images or PDF files. we can also output
any text, such as XHTML and XML.
Department of CSE.BVCOE
Why we are using It?
 It runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
It is compatible with almost all servers used today (Apache, IIS, etc.)
It supports a wide range of databases abd create dynamic website.
It is free. Download it from the official PHP resource: www.php.net
It is easy to learn and runs efficiently on the server side
What's new in It
It is much faster than the previous popular stable release (PHP 5.6)
It has improved Error Handling
It supports stricter Type Declarations for function arguments
It supports new operators (like the spaceship operator: <=>)

Department of CSE.BVCOE
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
Simple program to start:
<!DOCTYPE html>
<html><body>
<?php
$a = "and like PHP";
echo "I love $a"; ?> </body></html>
Output: I love and like PHP
<? php ?> it is the php syntax
Basic PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
Basic syntax : <?php // PHP code goes here ?>
Department of CSE.BVCOE
✓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" is used to output the text "Hello World!" on a web page:
<!DOCTYPE html>
<html>
<body>
<h1>My first simple PHP syntax using program </h1>
<?php
echo "Hello Friends you all are welcome in the World! of PHP";
?>
</body>
</html>
OUTPUT:
Department of CSE.BVCOE
Note: PHP statements end with a semicolon (;).
PHP is not Case Sensitivity
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are
not case-sensitive but variables are case-sensitive.
In the example below, all three echo statements below are equal and legal:
<!DOCTYPE html>
<html>
<body>
<?php OUTPUT:
Hello World!
ECHO "Hello World!<br>"; Hello World!
echo "Hello World!<br>"; Hello World!
Hello World!
EcHo "Hello World!<br>";
ecHO "Hello World!<br>";
?>
</body>
</html>
Department of CSE.BVCOE
• Note: However; all variable names are case-sensitive!
• Look at the example 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:
• <!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>

Department of CSE.BVCOE
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 */
Variables are "containers" for storing information.
Declaring PHP Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable.
<!DOCTYPE html>
<html><body>
<?php
$x = 5;
Department of CSE.BVCOE
$y = "John";
echo $x;
echo "<br>";
echo $y;
?>
</body></html>
OUTPUT:
5
John
PHP Variables
A variable can have a short name (like $x and $y) or a more descriptive name ($age,
$carname, $total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
Department of CSE.BVCOE
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
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 orofwithout
Department CSE.BVCOE parentheses: echo or echo().
Array

Department of CSE.BVCOE
An array stores multiple values in one single variable
<!DOCTYPE html>
<html>
<body> O/P:
array(3) {
<pre> [0]=>
<?php string(5) "Sonet"
[1]=>
$cars = array("Sonet", "BMW", "ToyotaPP"); string(3) "BMW"
var_dump($cars); [2]=>
string(8) "ToyotaPP"
?> }
</pre>
</body>
</html>
Department of CSE.BVCOE
• An array is a special variable that can hold many values under a single name,
and you can access the values by referring to an index number or name.
Array Types
In PHP, there are three types of arrays:
✓Indexed arrays - Arrays with a numeric index
✓Associative arrays - Arrays with named keys
✓Multidimensional arrays - Arrays containing one or more arrays
Indexed Arrays
✓In indexed arrays each item has an index number.
✓By default, the first item has index 0, the second item has item 1, etc.
Create and display an indexed array: Department of CSE.BVCOE
$cars = array(“SONETKIA", "BMW", "Toyota");
var_dump($cars);
Access Indexed Arrays
To access an array item you can refer to the index number.
• Display the first array item: O/P:
array(3) {
<?php [0]=>
string(5) "Sonet"
$cars = array(“SONETKIA", "BMW", "Toyota"); [1]=>
string(3) "BMW"
Echo $cars[0]; [2]=>
string(8) "ToyotaPP"
?> }
O/P: SONETKIA
Department of CSE.BVCOE
Change Value
• To change the value of an array item, use the index number:
For Example
<!DOCTYPE html>
<html>
<body> o/p:
<pre> array(3) {
[0]=>
string(8) "SONETKIA"
<?php [1]=>
$cars = array("SONETKIA", "BMW", "Toyota"); string(8) "Fordtest"
$cars[1] = "Fordtest"; [2]=>
string(6) "Toyota"
var_dump($cars);
}
?>
</pre>
</body>
</html>
Department of CSE.BVCOE
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a foreach loop,
like this:
<html>
SONETKIA
<body> BMW
<?php Toyota

$cars = array("SONETKIA", "BMW", "Toyota");


foreach ($cars as $x) {
echo "$x <br>";
}
?>
</body>
</html>
Department of CSE.BVCOE
Index Number
The key of an indexed array is a number, by default the first item is 0 and the
second is 1 etc., but there are exceptions.
New items get the next index number, meaning one higher than the highest
existing index.
So if you have an array like this:
$cars[0] = “SONETKIA";
$cars[1] = "BMW MOTO";
$cars[2] = "Toyota-VOLVO";

Department of CSE.BVCOE
• To access items from an associative array, use the key name:
• Access an item by referring to its key name.
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("brand" => “KIA ", "model" => “CARENS", "year" => 2024);
echo $cars["model"];
?>
</body>
</html>
• Double or Single Quotes
You can use both double and single quotes when accessing an array.
Department of CSE.BVCOE
<!DOCTYPE html>
<html>
<body>
<?php
$cars = array("brand" => "KIA", "model" => "CARENS", "year" => 2024);
echo $cars["model"];
echo "<br>"; CARENS
CARENS
echo $cars['model'];
?>
</body>
</html>
Department of CSE.BVCOE
Excecute a Function Item
Array items can be of any data type, including function.
To execue such a function, use the index number followed by parentheses ().
<html>
<body>
<?php I come from a function part!
function myFunction() {
echo "I come from a function part!";
}
$myArr = array("sonet", 15, myFunction);
$myArr[2]();
?>
</body>
</html>
Department of CSE.BVCOE
<html>
<body>
<?php
function myFunction() {
echo "I come from a function!";
}
$myArr = array("car" => "Sonet", "age" => 25, "message" => myFunction);
$myArr["message"]();
?>
</body>
</html>
O/P: I come from a function!
Department of CSE.BVCOE
Loop Through an Associative Array
To loop through and print all the values of an associative array, you can use a foreach loop, like this
<html>
<body>
<?php
$car = array("brand"=>"Kia", "model"=>"Carens", "year"=>2024);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
?>
</body>
</html>
o/p: brand: Kia
model: Carens
year: 2024
Department of CSE.BVCOE
PHP Multidimensional Arrays:
✓A multidimensional array is an array containing one or more arrays.
✓PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select
an element.
✓For a two-dimensional array you need two indices to select an element
✓For a three-dimensional array you need three indices to select an element
PHP - Two-dimensional Arrays
• A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).
• First, take a look at the following table:
Department of CSE.BVCOE
<html>
<body>
Name Stock Sold
<?php
Sonet 25 18
$cars = array (
array("Sonet",25,18), BMW 19 15
array("BMW",19,15),
Saab 65 27
array("Saab",65,27),
array("Land Rover",173,154) Land Rover 173 154
);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; Sonet: In stock: 25, sold: 18.
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; BMW: In stock: 19, sold: 15.
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; Saab: In stock: 65, sold: 27.
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>"; Land Rover: In stock: 173, sold: 154.
?>

</body>
</html> Department of CSE.BVCOE
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array(“Sonet",25,18), Name Stock Sold
array("BMW",19,15),
Sonet 25 18
array("Saab",65,27),
array("Land Rover",173,154) BMW 19 15
);
Saab 65 27
Land Rover 173 154

the two-dimensional $cars array contains four arrays, and it has two indices: row and column.
To get access to the elements of the $cars array we must point to the two indices (row and column):

Department of CSE.BVCOE
We can also put a for loop inside another for loop to get the elements of the $cars array ( point to the two indices)
<html><body><?php
$cars = array ( Row number 0
array("Sonet",25,18), Sonet
25
array("BMW",19,15),
18
array("Saab",65,27), Row number 1
array("Land Rover",173,154) BMW
); 19
for($row = 0; $row < 4; $row++) { 15
echo "<p><b>Row number $row</b></p>"; Row number 2
Saab
echo "<ul>";
65
for ($col = 0; $col < 3; $col++) { 27
echo "<li>".$cars[$row][$col]."</li>"; Row number 3
} echo "</ul>"; Land Rover
}?> 173
</body> </html> 154
Department of CSE.BVCOE
Function and Array

Department of CSE.BVCOE
The real power of PHP comes from its functions.
PHP has more than 1000 built-in functions, and in addition we can create our
own custom functions.
✓these functions can be called directly, from within a script, to perform a
specific task.
✓PHP reference for a complete list of the PHP built-in functions are:

Department of CSE.BVCOE
User Defined Functions
✓Besides the built-in PHP functions, it is possible to create your own functions.
✓A function is a block of statements that can be used repeatedly in a program.
✓A function will not execute automatically when a page loads.
✓A function will be executed by a call to the function.
Create a Function
A user-defined function declaration starts with the keyword function, followed by the
name of the function:
Example
function myMessage() {
echo "Hello world!";
}
A function name must start with a letter or an underscore. Function names are NOT
case-sensitive.
Department of CSE.BVCOE
Note: Give the function a name that reflects what the function does!
Call a Function
To call the function, just write its name followed by parentheses ():
Example <html><body>
function myMessage() { <?php
RONI KUMAR born in 1886
function familyName($fname,
HEUWAI KUMAR born in 199
echo "Hello Function!"; $year) {
SOMMA KUMAR born in 200
echo "$fname KUMAR born in
KOMMA KUMAR born in 200
} $year.<br>";
Gorge KUMAR born in 2003
}
myMessage(); // calling a function familyName("RONI“, ” 1886”);
familyName("HEUWAI“, “1999”);
familyName("SOMMA“, ”2001”);
familyName("KOMMA“,”2002”);
familyName("Gorge“, ”2003”);
?>
Department</body></html>
of CSE.BVCOE
Note: Give the function a name that reflects what the function does!
Call a Function
To call the function, just write its name followed by parentheses ():
Example <html><body>
function myMessage() { <?php
function familyName($fname) {
echo "Hello Function!"; echo "$fname KUMAR.<br>";
}
} familyName("RONI“);
familyName("HEUWAI“);
myMessage(); // calling a function familyName("SOMMA“);
familyName("KOMMA");
familyName("Gorge");
?>
</body></html>

Department of CSE.BVCOE
Default Argument Value
The following example shows how to use a default parameter. If we call the
function setHeight() without arguments it takes the default value as argument:
<!DOCTYPE html>
<html> The height is : 350
<body> The height is : 60
<?php The height is : 135
function setHeight($minheight = 60) { The height is : 80
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
Department of CSE.BVCOE
Functions - Returning values
To let a function return a value, use the return statement:
Example
function sum($x, $y) {
$z = $x + $y; 5 + 10 = 15
return $z; 7 + 13 = 20
2+4=6
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
Department of CSE.BVCOE
Operators in PHP

Department of CSE.BVCOE
Operating in PHP
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
✓Conditional assignment operators
Department of CSE.BVCOE
✓PHP Arithmetic Operators
The PHP arithmetic operators are used with numeric values to perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
Operat Name Example Result
or
+ Addition $x + $y Sum of $x and $y <!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
- Subtract $x - $y Difference of $x and $y <?php
ion $x = 10; <?php
* Multipli $x * $y Product of $x and $y $y = 6; $x = 10;
cation echo $x + $y; $y = 8;
?> $z=$x -$y;
/ Division $x / $y Quotient of $x and $y echo $z;
</body> ?>
** Expone $x ** $y Result of raising $x to </html> </body>
ntiation the $y'th power o/p: 16 </html>
Note : similar for -,*,/ o/p: 2
% Modulu $x % $y RemainderDepartment
of $x of CSE.BVCOEetc.
s divided by $y
PHP Assignment Operators
✓The PHP assignment operators are used with numeric values to write a value to a variable.
✓The basic assignment operator in PHP is "=". It means that the left operand gets set to the
value of the assignment expression on the right.
<!DOCTYPE html>
Assignment Same as... Description
<html>
x=y x=y The left operand gets set <body>
to the value of the
expression on the right <?php
$x = 15;
x += y x=x+y Addition $x %= 4;
echo $x;
?>
x -= y x=x-y Subtraction </body>
x *= y x=x*y Multiplication </html>
o/p: 3
x /= y x=x/y Division
x %= y x=x%y Modulus Department of CSE.BVCOE
PHP Comparison Operators:The PHP comparison operators are used to compare two values
(number or string):
Operator Name Example Result
== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same
type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the
same type

> Greater than $x > $y Returns true if $x is greater than $y


Department of CSE.BVCOE
• PHP Increment / Decrement Operators,The PHP increment operators are
used to increment a variable's value.The PHP decrement operators are used
to decrement a variable's value.
Operator Name Same as... Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one

Department of CSE.BVCOE
PHP Logical Operators
The PHP logical operators are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true

xor Xor $x xor $y True if either $x or $y is true, but not both

&& And $x && $y True if both $x and $y are true

|| Or $x || $y True if either $x or $y is true

! Not !$x True if $x is not true

Department of CSE.BVCOE
• PHP String Operators
• PHP has two operators that are specially designed for strings.
Operator Name Example Result
. Concatenation $txt1 . $txt2 Concatenation of $txt1 and $txt2
.= Concatenation $txt1 .= $txt2 Appends $txt2 to $txt1
assignmen

<!DOCTYPE html>
<html>
<body>
<?php
$txt1 = "Hello";
$txt2 = " world!";
$txt1 .= $txt2;
echo $txt1;
?>
</body> Department of CSE.BVCOE
</html> O/P : Hello world!
PHP Array Operators, PHP array operators are used to compare arrays.

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y Returns true if $x and $y have the same key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same key/value pairs in the same
order and of the same types
!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y

Department of CSE.BVCOE
<!DOCTYPE html>
<html>
<body>
<!DOCTYPE html>
<html> <?php
<body> $x = array("a" => "red", "b" => "green");
<?php $y = array("c" => "blue", "d" => "yellow");
$x = array(“s" => "red", “t" => "green"); var_dump($x != $y);
$y = array(“s" => "red", “t" => "green"); ?>
var_dump($x != $y); </body>
?> </html>
</body>
</html> o/p: bool (true)

O/P: bool(false)

Department of CSE.BVCOE
PHP Conditional Assignment Operators
The PHP conditional assignment operators are used to set a value depending on
conditions:
Operat Name Example Result
<html><body>
or
<?php
// variable $user is the value of
$_GET['user'] ?: Ternary $x Returns the value of $x.
// and 'anonymous' if it does = expr1 ? expr2 : ex The value of $x is expr2 if expr1 = TRUE.
not exist pr3 The value of $x is expr3 if expr1 = FALSE
echo $user = $_GET["user"] ??
"MAHESH KUMAR";
echo("<br>"); ?? Null $x = expr1 ?? expr2 Returns the value of $x.
// variable $color is "red" if coalescing The value of $x is expr1 if expr1 exists,
$color does not exist or is null and is not NULL.
echo $color = $color ?? "green"; If expr1 does not exist, or is NULL, the
?> value of $x is expr2.
</body></html>
Department of CSE.BVCOE
PHP if Statements: Conditional statements are used to perform different actions based on different conditions.
Conditional Statements
Very often when you write code, you want to perform different actions for different conditions
In PHP we have the following conditional statements:

if statement - executes some code if one condition is true


if...else statement - executes some code if a condition is true and another code if that condition is false
if...elseif...else statement - executes different codes for more than two conditions
switch statement - selects one of many blocks of code to be executed

Department of CSE.BVCOE
if Statement
if statement executes some code if one condition is true.
Syntax
if (condition) {
// code to be executed if condition is true;
} <!DOCTYPE html>
<html>
EXAMPLE :
O/P: <body>
<!DOCTYPE html> <?php
<html> Have a good day!
$t = 15;
<body> if ($t < 20) {
<?php echo “I am Good and Have a good day!";
if (5 > 3) { }
?>
echo "Have a good day!";
</body>
} </html>
?> O/P:
</body> I am Good and Have a good day!
</html>
Department of CSE.BVCOE
PHP if...else Statements
if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
Syntax
if (condition) { // code to be executed if condition is true;
} else { // code to be executed if condition is false; }
Example
<html><body>
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?> </body>
</html>
Department of CSE.BVCOE
T

if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}
Example
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
Department of CSE.BVCOE
Short Hand If
To write shorter code, you can write if statements on one line.
<html><body>
<?php
$a = 5; O/P: Hello
if ($a < 10) $b = "Hello";
echo $b
?></body></html>
if...else statements can also be written in one line, but the syntax is a bit different.
<html>
<body>
?php O/P : Good Bye
$a = 13;
$b = $a < 10 ? "Hello" : "Good Bye";
echo $b;
?>
</body>
</html>
Note: This technique is known as Ternary Operators, or Conditional Expressions.
Department of CSE.BVCOE
Nested if Statement
can have if statements inside if statements, this is called nested if statements.
<html>
<body>
<?php
$a = 13; O/P: Above 10 but not above 20
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}}
?>
</body>
</html>
Department of CSE.BVCOE
switch Statement
The switch statement is used to perform different actions based on different conditions.
switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax <html><body>
switch (expression) { <?php
$favcolor = "red"; o/p: MY favorite color is red!
case label1:
switch ($favcolor) {
//code block case "red":
break; echo “MY favorite color is red!";
case label2: break;
case "blue":
//code block;
echo "Your favorite color is blue!";
break; break;
case label3: case "green":
//code block echo "Your favorite color is green!";
break; break;
default:
default: echo "Your favorite color is neither red, blue, nor green!";
//code block }
} ?>
</body></html> Department of CSE.BVCOE
Loops
✓Often when we write code, you want the same block of code to run over and
over again a certain number of times. So, instead of adding several almost
equal code-lines in a script, we can use loops.
✓Loops are used to execute the same block of code again and again, as long as
a certain condition is true.
In PHP, we have the following loop types:
✓while - loops through a block of code as long as the specified condition is true
✓do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
✓for - loops through a block of code a specified number of times
✓foreach - loops through a block of code for each element in an array

Department of CSE.BVCOE
while Loop
The while loop executes a block of code as long as the specified condition is
true.
Example
$i = 1;
12345
while ($i < 6) {
echo $i;
$i++;
}

Department of CSE.BVCOE
do while Loop
✓The do...while loop - Loops through a block of code once, and then repeats
the loop as long as the specified condition is true.
do...while Loop
✓The do...while loop will always execute the block of code at least once, it will
then check the condition, and repeat the loop while the specified condition is
true. <html>
<body>
<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
</body>
</html>
o/p:12345
Department of CSE.BVCOE
for Loop
The for loop is used when you know how many times the script should run.
Syntax
for (expression1, expression2, expression3) { The number is: 0
The number is: 1
// code block <!DOCTYPE html> The number is: 2
<html> The number is: 3
} <body> The number is: 4
The number is: 5
for ($x = 0; $x <= 10; $x++) { <?php The number is: 6
for ($x = 0; $x <= 10; $x++) { The number is: 7
echo "The number is: $x <br>"; echo "The number is: $x <br>"; The number is: 8
} The number is: 9
} ?> The number is: 10

</body>
</html>

Department of CSE.BVCOE
The break
statement can be used to jump out of different kind of loops.
Break in For loop
The break statement can be used to jump out of a for loop.
<html> <body> The number is: 0
<?php The number is: 1
for ($x = 0; $x < 10; $x++) { The number is: 2
The number is: 3
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
</body></html>
Department of CSE.BVCOE
Break in While Loop
The break statement can be used to jump out of a while loop.
Break Example
$x = 0;
while($x < 10) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
$x++;
}

Department of CSE.BVCOE
Continue
The continue statement can be used to jump out of the current iteration of a
loop, and continue with the next.
Continue in For Loop
The continue statement stops the current iteration in the for loop and continue
with the next.
for ($x = 0; $x < 10; $x++) { The number is: 0
The number is: 1
if ($x == 4) { The number is: 2
The number is: 3
continue; The number is: 5
The number is: 6
} The number is: 7
The number is: 8
echo "The number is: $x <br>"; The number is: 9
}
Department of CSE.BVCOE
Continue in While Loop
The continue statement stops the current iteration in the while loop and
continue with the next.
$x = 0;
while($x < 10) { The number is: 1
The number is: 2
if ($x == 4) { The number is: 3
The number is: 5
continue; The number is: 6
The number is: 7
} The number is: 8
The number is: 9
echo "The number is: $x <br>"; The number is: 10

$x++;
}

Department of CSE.BVCOE

You might also like