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

PHP Module 3

web programming using PHP - Calicut University 5th sem BSc Computer science

Uploaded by

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

PHP Module 3

web programming using PHP - Calicut University 5th sem BSc Computer science

Uploaded by

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

UNIT III S.

UNIT- III
INTRODUCTION TO PHP

PHP - INTRODUCTION

PHP started out as a small open source project “Personal Home Page” that gave
users access to their server logs and to process online form. Rasmus Lerdorf
created the first version of PHP way back in 1994.

 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

 PHP is a server side scripting language that is embedded in HTML. It is


used to manage dynamic content, databases, session tracking, even build
entire e-commerce sites.

 PHP supports a large number of major protocols such as POP3, IMAP,


and LDAP.

 PHP Syntax is C-Like.

 It runs on different platforms such as Windows, Linux, Unix, etc.

 It supports many databases such as MySQL, Oracle, PostgreSQL etc.

Characteristics of PHP

Five important characteristics make PHP are −


 Simplicity
 Efficiency
 Security
 Flexibility
 Familiarity
UNIT III S.A

Common uses of PHP

 Efficient storage and delivery of information:

 Customised user experience: Servers can store and use information


about clients to provide a convenient and customized user experience.

 Controlled access to content: Server-side programming allows sites to


restrict access to authorized users and serve only the information that a
user is permitted to see.

 Store session/state information: Server-side programming allows


developers to make use of sessions, a mechanism that allows a server to
store information on the current user of a site

 Access and set cookies

 Data encryption: It can encrypt data.

 Form handling, i.e. gather data from files, save data to a file.

 Notifications and communication: Servers can send general or user-


specific notifications through the website itself or via email, SMS, instant
messaging, video conversations, or other communications services.

 Data analysis: Server-side programming can be used to refine responses


based on analysis of this data. For example, Amazon and Google both
advertise products based on previous searches (and purchases).

ROLE OF WEB SERVER SOFTWARE

Web server is a computer where the web content is stored. Basically web
server is used to host the web sites but there exists other web servers also such
as gaming, storage, FTP, email etc. The top web servers today are: Apache, IIS
(Internet Information Services) by Microsoft, GWS (Google Web Server)
by Google etc.
UNIT III S.A

Web site is collection of web pages and web server is software that responds to
the request for web resources. The web server run web server software (called
as daemon). It understands HTTP.

Web Server Working

Web server respond to the client request in either of the following two ways:
 Sending the file to the client associated with the requested URL.
 Generating response by invoking a script and communicating with
database

1. Obtaining the IP Address from domain name: Our web browser first
obtains the IP address of the site. It can obtain the IP address in 2 ways-

 By searching in its cache.


 By requesting one or more DNS (Domain Name System) Servers. 

2. Browser requests the full URL: After knowing the IP Address, the
browser now demands a full URL from the web server.

3. Web server responds to request: The web server responds to the browser
by sending the desired pages, and in case, the pages do not exist or some
other error occurs, it will send the appropriate error message.
For example:
You may have seen Error 404, while trying to open a webpage, which is
the message sent by the server when the page does not exist.
Another common one is Error 401 when access is denied to us due to
incorrect credentials, like username or password, provided by us.

4. Browser displays the web page: The Browser finally gets the webpages
and displays it, or displays the error message.
UNIT III S.A

Key Points –Web Server -Client Communication

 When client sends request for a web page, the web server search for the
requested page. If requested page is found then it will send the page to
client with an HTTP response.
 If the requested web page is not found, web server will the send an
HTTP response: Error 404 Not found.
 If client has requested for some other resources then the web server will
contact to the application server and data store to construct the HTTP
response.

Features of web server

 Hosts one or more websites. A server can contain more than onewebsite.
 Configure log files settings such as where the log files are saved, what
data are included in the log file etc.
 Configure website security.
 Create FTP (File Transfer Protocol) sites. FTP sites allow transferring
files to and from the site.
 Configure custom error pages. It displays user friendly error messages.
(404 Page Not Found).
UNIT III S.A

SERVER SIDE SCRIPTING

Web servers are used to execute server side scripting. They are basically
used tocreate dynamic pages. It can also access the file system residing at web
server. Server-side environment that runs on a scripting language is a web-
server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages.
Languages used in server scripting are Ruby, PHP, ASP.NET, ADOBE
COLDFUSION etc.

 Customise responses based on user requirements.


 Server side scripts are not dependant on the browser.
 Greater flexibility. (Access to database, modify files).
 High security.
 Code not visible to the use.

PHP PROGRAMMING

The PHP Hypertext Preprocessor (PHP) is a programming language that allows


web developers to create dynamic content that interacts with databases. PHP is
basically used for developing web based software applications. PHP is a
general-purpose scripting language especially suited to web development.
Sample code:

<html>

<head>

<title>Hello World</title>

</head>

<body>

<?php

echo "Hello, World!";

?>
UNIT III S.A

</body>

</html>

It will produce following result −

Hello, World!

PHP Editors

Text editors and IDE’s are used to code PHP SCRIPT. It is saved using the
extension .php.

 Notepad++
 Eclipse
 Geany
 PHP Coder
 Netbeans IDE

INTRODUCING PHP SCRIPT IN HTML

The different ways of inserting PHP script are the following:

Basic PHP Syntax (Canonical PHP tags): A PHP script can be placed
anywhere in the document. A PHP script starts with <?php and ends with ?>:

The default file extension for PHP files is “.php”.

<?php

// PHP code goes here

?>

HTML script tags : HTML script tags look like this −

<script language = "php">

print “This uses HTML scripting syntax”;

</script>
UNIT III S.A

Short tags (Short-open (SGML-style) tags): Short or short-open tags look like
this −

<?

print “short tag sytax”;

?>

php.ini

--enable-short-tags configuration option when writing PHP


scripts using short tags

short_open_tag = on

ASP-style tags

ASP-style tags mimic the tags used by Active Server Pages to delineate code
blocks. ASP style tags look like this –

<%...%>

To use ASP-style tags, you will need to set the configuration option in your
php.ini file.

asp_tags = 0n

We can also insert PHP in HTML by putting it in a separate file and calling
them using include and require constructs.

The include or require statement takes all the text/code/markup that exists in the
specified file and copies it into the file that uses the include statement.

Including files is very useful when you want to include the same PHP,
HTML,or text on multiple pages of a website.
UNIT III S.A

include(“filename”);

require(“filename”);

or

include ‘filename’;

require ‘filename’;

PHP include and require Statements

It is possible to insert the content of one PHP file into another PHP file (before
the server executes it), with the include or require statement.

The include and require statements are identical, except upon failure:

 require will produce a fatal error (E_COMPILE_ERROR) and stop the


script
 include will only produce a warning (E_WARNING) and the script will
continue

Include files are helpful to

 include text files into a web page.


 define variable or constants and details of error messages.
 place commonly used functions inside the web pages.

Parsing a PHP Script.

 Web server send request to PHP parser which is built in the web server.

 PHP parser scans the requested file for php code.

 Parser executes the php code and places the result in the file.

 New output is send back to web server.

 Serve send the output to the web browser.

 Browser displays the output.


UNIT III S.A

COMMENTING PHP CODE

A comment is the portion of a program that exists only for the human reader.
PHP engine ignores a comment. There are two commenting formats in PHP −
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 a comment too. Each style comments only
print "An example with single line comments";
?>

Multi-lines comments − They are generally used to provide pseudocode


algorithms and more detailed explanations when necessary. The multiline style
of commenting is the same as in C.

Here are the example of multi lines comments.

<?php
/* This is a comment with multiline
Author : Mohammad Mohtashim
Purpose: Multiline Comments Demo

Subject: PHP
*/
print "An example with multi line comments";

?>
Php Is Whitespace Insensitive

PHP whitespace is insensitive means that it almost never matters how many
whitespace characters you have in a row.
UNIT III S.A

Php Is Case Sensitive

PHP is a case sensitive language. Try out following example −


<html>
<body>
<?php
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>

This will produce the following result –

Variable capital is 67
Variable CaPiTaL is

Statements Are Expressions Terminated By Semicolons


A statement in PHP is any expression that is followed by a semicolon (;). Any
sequence of valid PHP statements that is enclosed by the PHP tags is a valid
PHP program.

<?php

$greeting = "Welcome to PHP!";

?>
UNIT III S.A

PHP - VARIABLE

The main way to store information in a PHP program is by using a variable.

Here are the most important things to know about variables in PHP.

are assigned with the = operator, with the variable on the left-hand
side and the expression to be evaluated on the right.

- a variable does not know in


advance whether it will be used to store a number or a string of characters.

when necessary.

variables are Perl-like.

PHP DATA TYPES

PHP data types are used to hold different types of data or values. PHP supports
8 primitive data types that can be categorized further in 3 types:

1. Scalar Types (predefined)


2. Compound Types (user-defined)
3. Special Types

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


UNIT III S.A

1. array
2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. Resource
2. NULL

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:


An integer can be either positive or negative.
An integer must not contain decimal point.

Integer can be decimal (base 10), octal (base 8), or hexadecimal (base 16).

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


UNIT III S.A

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';


UNIT III S.A

?>

Output:

Hello Javatpoint

Hello $company

PHP Boolean

They have only two possible values either true or false. PHP provides a couple
of constants especially for use as Booleans: TRUE and FALSE, which can be
used like so −

if (TRUE)
print("This will always print<br>");

else
print("This will never print<br>");

<?php

$x = true;

$y =false;

var_dump($x);

?>

PHP Array

An array is a compound data type. It can store multiple values of same data type
in a single variable.
UNIT III S.A

Example:

<?php

$Subject = array ("Python", "C", "PHP");

var_dump($Subject); //the var_dump() returns the datatype and values

echo "</br>";

echo "Array Element1: $Subject[0] </br>";

echo "Array Element2: $Subject[1] </br>";

echo "Array Element3: $Subject[2] </br>";

?>

Output:

Array Element1: Python

Array Element2: C

Array Element3: PHP

PHP Object

Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared. An object is a data type that stores
data and also information about how to process that data. An object is a specific
instance of a class. Objects are created based on this template via the new
keyword.

Every object has properties and methods corresponding to those of its parent
class. Every object instance is completely independent, with its own properties
and methods
First we must declare a class of object. For this, we use the class keyword. A
class is a structure that can contain properties and methods:
UNIT III S.A

<?php

class Color

// create an object

$blue = new Color;

var_dump($blue);

?>

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.

<?php

// Open a file for reading

$handle = fopen("note.txt", "r");

var_dump($handle);

echo "<br>";

?>

PHP Null

Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters. It represents empty variable in PHP. It does not
mean blank space or zero.

 The special type of data type NULL defined a variable with no predefined
value.
 It has been assigned NULL specifically.
 It has been erased using unset().
UNIT III S.A

Example:

<?php

$nl = NULL;

echo $nl; //it will not give any output

?>

Type juggling (Implicit Conversion)


PHP does not require (or support) explicit type definition in variable
declaration; a variable's type is determined by the context in which the variable
is used. It automatically converts value from one type to another whenever
required. This is called implicit conversion /implicit casting or type juggling.

Eg: Whenever performing arithmetic operations on different data types PHP try
to converts string type to integer first.

<?php

$var1 = “25 rupees”;

$var2 =10;

$sum = $var1+ $var2;

echo $sum;

?>

Type casting
The process of explicitly converting values from one data type to another is
called type casting or explicit conversion. PHP’s cast types are:

o (int), (integer) - cast to integer


o (bool), (boolean) - cast to boolean
o (float), (double), (real) - cast to float
o (string) - cast to string
o (array) - cast to array
o (object) - cast to object
o (unset) - cast to NULL
UNIT III S.A

<?php
$foo = 10; // $foo is an integer
$bar = (bool) $foo; // $bar is a boolean
?>

Defined constants

A constant value cannot be changed during the execution of the script. By


default, a constant is case-sensitive. By convention, constant identifiers are
always uppercase. A constant name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores. If you have defined a
constant, it can never be changed or undefined.
Constants are global.
define(name, value, case-insensitive)

example:
define(“PI”, 3.141592);
echo PI;

define(“MSG”, “helloo”, true);


echo msg;

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.

<?php
const MESSAGE="Hello const by JavaTpoint PHP";
echo MESSAGE;
?>
UNIT III S.A

Differences between constants and variables are

 There is no need to write a dollar sign ($) before a constant, where as in


Variable a dollar sign is required. 
 Constants cannot be defined by simple assignment, they may only be
defined using the define() function.
 Constants may be defined and accessed anywhere without regard to
variable scoping rules. 
 Once the Constants have been set, may not be redefined or undefined.

constant() function

As indicated by the name, this function will return the value of the constant.

<?php
define("MINSIZE", “HELLO”);

echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in
constants.

PHP Magic constants

PHP provides a large number of predefined constants to any script which it


runs.
There are five magical constants that change depending on where they are
used.

Sr.No Name & Description

1 LINE
The current line number of the file.
UNIT III S.A

2 FILE
The full path and filename of the file.

3 FUNCTION
The function name.

4 CLASS
The class name.

5 METHOD
The class method name.

PHP ECHO AND PRINT STATEMENTS

There are two basic ways to get the output in PHP:

o echo
o print

echo and print are language constructs, and they never behave like a function.
Therefore, there is no requirement for parentheses. However, both the
statements can be used with or without parentheses. We can use these
statements to output variables or strings.

echo and print comparison

echo
o echo is a language construct, which is used to display the output.
o echo can be used with or without parentheses.
o echo does not return any value.
o We can pass multiple strings separated by comma (,) in echo.
o echo is marginally faster than print statement.
UNIT III S.A

print
o print is also a language construct, used as an alternative to echo at many
times to display the output.
o print can be used with or without parentheses.
o print always returns an integer value, which is 1.
o Using print, we cannot pass multiple arguments.
o print is slower than echo statement.

Echo statement

The echo statement is a language construct that can output one or more strings.
It can output any values such as number, variables, strings etc.

The parameters must not be enclosed within parenthesis. (echo or echo() ).

Display Strings of Text


The following example will show you how to display a string of text with the
echo statement:
<?php
// Displaying string of text
echo "Hello World!";
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
?>
The output of the above PHP code will look something like this:
Hello World!

This string was made with multiple parameters.

Display Variables
The following example will show you how to display variable using the echo
statement:
<?php
$txt = "Hello World!";
$num = 123456789;
$colors = array("Red", "Green", "Blue");
UNIT III S.A

// Displaying variables
echo $txt;
echo "<br>";
echo $num;
echo "<br>";
echo $colors[0];
?>
The output of the above PHP code will look something like this:

Hello World!

123456789

Red

The print Statement


You can also use the print statement (an alternative to echo) to display output to
the browser. Like echo the print is also a language construct, not a real function.
So you can also use it without parentheses like: print or print().

Both echo and print statement works exactly the same way except that the print
statement can only output one string, and always returns 1. That's why the
echo statement considered marginally faster than the print statement since it
doesn't return any value.
Print accepts only one argument.

<?php

$var=”hello”

print $var;

print ("<h2>PHP is Fun!</h2>");

print "Hello world!<br>";

print "I'm about to learn PHP!";

?>
UNIT III S.A

VARIABLE SCOPE

The scope of a variable is defined as the range in the program under which it
can be accessed. In other words, "The scope of a variable is the portion of the
program within which the variable is defined and can be accessed." A variable
can be declared anywhere in the PHP script.

PHP variables can have four scopes.

 Local variable
 Function parameter
 Global variable
 Static Variable

When a variable is accessed outside its scope it will cause PHP error Undefined
Variable.

1. Local Scope Variables

A variable declared within a function is considered as a local variable. A local


scope is a restricted boundary of a variable within which code block it is
declared. That block can be a function or class. These local variables have their
scope only in that particular function in which they are declared. This means
that these variables cannot be accessed outside the function.

Here we have declared a variable $count inside this function. This variable is
said to be a local variable of this function and it is in the local scope of the
function block.

<?php

function calculate_count() {

$count = 5;

echo $count++;

?>
UNIT III S.A

Local variables will be destroyed once the end of the code block is reached.
Hence the same named variables can be declared within different local scopes.

2. Global Scope Variables

The global scope provides widespread access to the variable declared in this
scope. Variables in global scope can be accessed from anywhere in the program.
i.e from outside a function or class independent of its boundary.

PHP global variables can be defined by using global keyword. If we want to use
global variables inside a function, we have to prefix the global keyword with the
variable. The following code shows a code block to learn how to use the global
keyword with a PHP variable to declared it as a global variable.

<?php

$count = 0;

function calculate_count()

global $count;

echo $count++ . "<br/>";

calculate_count();

echo $count;

?>

3. Static Variables (local scope)

A static variable is a variable with local scope. But it is not destroyed outside
the scope boundary. A variable can be defined by using the ‘static’ keyword
inside a function.
UNIT III S.A

A static variable does not lose its value when the program execution goes past
the scope boundary. But it can be accessed only within that boundary. Let me
demonstrate it using the following example code,

<?php

function counter()

static $count = 0;

echo $count;

$count++;

?>

The above counter function has the static variable ‘count’ declared within its
local scope. When the function execution is complete, the static count variable
still retains its value for further computation.

4. Function Parameters (Local Scope)

Function parameters (arguments) are local variables defined within the local
scope of the function on which it is used as the argument.

Function parameters are declared after the function name and inside
parentheses. They are declared much like a typical variable would be −

<?php
$x=10;
print "value outside function $x \n";
function multiply ($x)
{
$x = $x * 10;
Print "value inside function $x \n";
}
UNIT III S.A

multiply($x);
print "value outside function $x \n";
?>
This will produce the following result −
value outside function 10

value inside function 100

value outside function 10

PREDEFINED VARIABLES

Predefined variables are accessible from anywhere within the PHP script,
regardless of scope. This gives information about user session, users operating
environment etc. Some of the predefined variables are called super globals,
which means they are present and available anywhere in the script.

Some of the super globals are listed below.

PHP SUPERGLOBALS

Sr.No Variable & Description

1 $GLOBALS
This array contains a reference to every variable which is currently available within
the global scope of the script.

2
$_SERVER
This is an array containing information such as headers, paths, and script locations.
The entries in this array are created by the web server.

3 $_GET
UNIT III S.A

An associative array of variables passed to the current script via the HTTP GET
method.

4
$_POST
An associative array of variables passed to the current script via the HTTP POST
method.

5
$_FILES
An associative array of items uploaded to the current script via the HTTP POST
method.

6
$_COOKIE
An associative array of variables passed to the current script via HTTP cookies.

7 $_SESSION
An associative array containing session variables available to the current script.

PHP OPERATORS

Operators are used to perform operations on some values. In other words,


operators that takes some values, performs some operation on them and gives a
result.

PHP divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators (Relational operators)
 Increment/Decrement operators
 Logical operators
 Bitwise operators
 String operators
 Conditional assignment operators
UNIT III S.A

PHP Arithmetic Operators

The PHP arithmetic operators are used with numeric values to perform common
arithmetical operations, such as addition, subtraction, multiplication etc.

Operator Name Example Result

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

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

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

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


by $y

** Exponentiation $x ** $y Result of raising $x to the


$y'th power

PHP Assignment Operators

The PHP assignment operators are used 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.
UNIT III S.A

Assignment Operation Description

$x = $y $x = $y The left operand


gets set to the value
of the expression on
the right.

$x += $y $x = $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 quotient

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

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 sametype

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


$y
UNIT III S.A

< Less than $x < $y Returns true if $x is less than $y

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


or equal to or equal to $y

<= Less than or $x <= $y Returns true if $x is less than or


equal to equal to $y

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 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
UNIT III S.A

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 aretrue

Or Or $x or $y True if either $x or $y istrue

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 aretrue

|| Or $x || $y True if either $x or $y istrue

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

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.
UNIT III S.A

Operator Name Example Explanation


& And $a & $b Bits that are 1 in both $a
and $b are set to 1,
otherwise 0.
| Or $a | $b Bits that are 1 in either $a
(Inclusive or $b are set to 1
or)
^ Xor $a ^ $b When one and only one
(Exclusive of the expression evaluates
or) to true theresult is true.
~ 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
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


assignment $txt1
UNIT III S.A

PHP Conditional Assignment Operators

The PHP conditional assignment operators are used to set a value depending on
conditions:

Operator Name Example Result

?: Ternary $x = expr1 ? expr2 : expr3; Returns the value of $x.


The value of $x
is expr2 if expr1 =
TRUE.
The value of $x
is expr3 if expr1 =
FALSE
UNIT III S.A

PHP – CONDITIONAL STATEMENTS (Branching Statements)

Code execution can be grouped into categories as shown below

 Sequential – this one involves executing all the codes in the order in
which they have been written.
 Decision – this one involves making a choice from a number of options.
The code executed depends on the value of the condition. 

A control structure is a block of code that decides the execution path of a


program depending on the value of the set condition.

Decision making codes in programming are called control- flow structures or


branching structures. These statements are used to take decision based on the
different condition.

Conditional statements are used in code to make decisions. PHP supports


following decision making statements −

 if statement - The if statement executes some code if specified condition


is true.

 if...else statement – The if statement is executed when a condition is true


and else is executed when the given condition is false. 
 if….elseif..else statement − The if...else statement is used to execute a
set of code if one of the several condition is true
 switch statement – The switch statement is used to select one of many
blocks of code to be executed. This is a selection statement. The switch
statement is used to avoid long blocks of if..elseif..else code.
The if Statement

The if statement executes some code if specified condition is true.

Syntax

if (condition) {

code to be executed if condition is true;

}
UNIT III S.A

Example

<html>
<body>

<?php
$a = 100;
$b = 20;

if ($a>$b)
echo "$a is the larger number” ;

?>

</body>
</html>

The If...Else Statement


The if…else statement provides an alternative choice. If a condition is true then
a particular group of statements are executed and if the condition is false then
the else part is executed.

Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;

Example
<html>
<body>

<?php

$a = 100;
$b = 200;
UNIT III S.A

if ($a>$b)
echo "$a is the larger number” ;
else
echo "$b is larger number";
?>

</body>
</html>

The if ….elseIf else Statement

It combines multiple if…elseif …else statements.

Syntax
if (condition1)
code to be executed if condition1 is true;
elseif (condition2)
code to be executed if condition2 is true;
elseif(condition3)
code to be executed if condition3 is true;
else
code to be executed if all other conditions are false;

<html>
<body>

<?php
$d = date("D");

if ($d == "Fri")
echo "Have a nice weekend!";

elseif ($d == "Sun")


echo "Have a nice Sunday!";
else
echo "Have a nice day!";
?>
UNIT III S.A

</body>
</html>
It will produce the following result −
Have a nice day!

The Switch Statement

If one of many blocks of code to be executed, the Switch statement is used.


The switch statement is used to avoid long blocks of if..elseif..else code.

It only executes a single block of code depending on the value of the condition.
The switch statement selects one of many blocks of code to be executed. It is a
multiple case selection statement.

If no condition has been met then the default block of code is executed.

First we have a single expression n (most often a variable), that is evaluated


once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that
case is executed. Use break to prevent the code from running into the next case
automatically.

Syntax

switch (expression )
{
case value: statement1;
break;

case value2: statement2;


break;

case value3: statement3;


break;

default: default case;


}
UNIT III S.A

Example
<html>
<body>

<?php
$d = date("D");

switch ($d)
{
case "Mon":
echo "Today is Monday";
break;

case "Tue":
echo "Today is Tuesday";
break;

case "Wed":
echo "Today is Wednesday";
break;

case "Thu":
echo "Today is Thursday";
break;

case "Fri":
echo "Today is Friday";
break;

case "Sat":
echo "Today is Saturday";
break;

case "Sun":
echo "Today is Sunday";
break;
UNIT III S.A

default:
echo "Default value”;
}
?>

</body>
</html>
It will produce the following result −
Today is Tuesday

PHP - LOOP STATEMENTS


Loops in PHP are used to execute the same block of code a specified number of
times. Each passage through loop is called iteration. It saves time and effort by
doing tasks within a program repeatedly. PHP supports following four loop
types.
 for − loops through a block of code a specified number of times until the
condition is met.
 while − loops through a block of code if and as long as a specified
condition is true
 do...while − loops through a block of code once, and then repeats the
loop as long as a special condition is true.
 foreach − loops through a block of code for each element in an array.

The for loop statement

The for loop, loops through a block of code a specified number of times. It
repeats the block of code until a certain condition is met.

Syntax
for (initialization; condition; increment/derement)
{
code to be executed;
}
UNIT III S.A

The initializer is used to set the start value for the counter of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Initialisation only happens once.

Example
<!DOCTYPE html>
<html>
<body>
<?php
for ($i = 0; $i <= 10; $i++)
{
echo "The number is: $i <br>";
}
?>
</body>
</html>
This will produce the following result −

The number is: 0

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The number is: 6

The number is: 7

The number is: 8

The number is: 9

The number is: 10


UNIT III S.A

The while loop statement

The while statement will execute a block of code as long as a test expression is
true.
If the test expression is true then the code block will be executed. After the
code has executed the test expression will again be evaluated and the loop will
continue until the test expression is found to be false.

Syntax
while (condition)
{
code to be executed;
}

Example
<?php
$x = 1;

while($x <= 5)
{
echo "The number is: $x <br>";
UNIT III S.A

This will produce the following result –

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The do...while loop statement

The do...while statement will execute a block of code at least once - it then
will repeat the loop as long as a condition is true.

Syntax
do
{
code to be executed;
}
while (condition);

Example
<!DOCTYPE html>
<html>
<body>

<?php
$x = 1;

do
{
echo "The number is: $x <br>";
UNIT III S.A

$x++;
} while ($x <= 5);
?>

</body>
</html>

This will produce the following result –

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The foreach loop statement

The foreach statement is used to loop through arrays. For each pass, the value
of the current array element is assigned to $value and the array pointer is
moved by one and in the next pass next element will be processed.

Syntax
foreach (array as $value)
{
code to be executed;
}

Example
Try out following example to list out the values of an array.

<html>
<body>

<?php
$array1 = array( 1, 2, 3, 4, 5);
UNIT III S.A

foreach( $array1 as $value )


{
echo "Value is $value <br />";
}
?>
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5

JUMP STATEMENTS

The break statement

The PHP break keyword is used to terminate the execution of a loop before it
ends. It is a jump statement.
The break statement is situated inside the statement block. It gives you full
control and whenever you want to exit from the loop you can come out. After
coming out of a loop the immediate statement after the loop will be executed.
UNIT III S.A

Example
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x < 10; $x++)
{
if ($x == 4)
{
break;
}
echo "The number is: $x <br>";
}
?>

</body>
</html>
This will produce the following result –
The break statement can be used to jump out of a loop.
The number is: 0
The number is: 1
The number is: 2
The number is: 3

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it
does not terminate the loop. Continue statement is also termed as jump
statement.
Just like the break statement the continue statement is situated inside the
statement block. For the pass encountering continue statement, rest of the loop
code is skipped and next pass starts.
UNIT III S.A

Example
<!DOCTYPE html>
<html>
<body>

<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>

</body>
</html>
This will produce the following result −
The number is: 0

The number is: 1

The number is: 2

The number is: 3

The number is: 5

The number is: 6

The number is: 7

The number is: 8

The number is: 9


UNIT III S.A

PHP USER-DEFINED FUNCTIONS

PHP has over 1000 built-in functions that can be called directly, from within a
script, to perform a specific task. Besides the built-in PHP functions, it is
possible to create user defined 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. 

A function is a reusable block of code that performs a specific task.


Code reusability is the main advantage of function. Functions are easy to
understand and it reduces the line of code. This block is defined with function
keyword and is given a name that starts with an alphabet or underscore.
Functions help to implement modularity. It divides a large program into several
manageable units
The function body is enclosed within curly braces. This function may be called
from anywhere within the program any number of times. Function names are
NOT case-sensitive.
Syntax
//define a function
function myfunction($param1, $param2, ... $param)
{
statement1;
statement2;
..
return $val;
}
//call function
myfunction($arg1, $arg2, ... $argn);
UNIT III S.A

Example:

<?php

//function definition

function sayHello()

echo "Hello World!";

//function call

sayHello();

?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just


like a variable.

Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the
familyName() function is called, we also pass name value to the function and
the name is used inside the function.

<!DOCTYPE html>

<html>

<body>

<?php

function familyName($fname) {

echo "Helllo $fname .br>";

}
UNIT III S.A

familyName("Jane");

familyName("Alan");

?>

</body>

</html>

Following example takes two integer parameters and add them together and
then print them.

<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>
UNIT III S.A

PHP Function: Default Parameter Value (optional parameters)

We can specify a default value for parameters in function. While calling PHP
function if you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.

<?php
function sayHello($name="Aravi")
{
echo "Hello $name<br/>";
}
sayHello("Rajesh");
sayHello(); //passing no value
sayHello("John");
?>

Output:

Hello Rajesh
Hello Aravi
Hello John

Returning value from function

A function can return a value back to the script that called the function using the
return statement. The value may be of any type, including arrays and objects.

<?php
// Defining function
function getSum($num1, $num2)
{
$total = $num1 + $num2;
return $total;
}

// Printing returned value


echo getSum(5, 10); // Outputs: 15
?>
UNIT III S.A

The return keyword is used to return value back to the part of program,
from where it was called. The returning value may be of any type including
the arrays and objects. Normally a function cannot return multiple values. But
the similar result can be obtained using arrays.

<?php

function add($num1, $num2, $num3)


{
$sum = $num1 + $num2 + $num3;

return $sum; //returning the product


}

$retValue = add(2, 3, 5);


echo "The add is $retValue";

?>

Passing arguments by Value and Passing arguments by reference

In PHP there are two ways you can pass arguments to a function: by
value and by reference. By default, function arguments are passed by value so
that if the value of the argument within the function is changed, it does not get
affected outside of the function.

 Pass by Value: On passing arguments using pass by value, the value of the
argument gets changed within a function, but the original value outside the
function remains unchanged. That means a copy of the original value is
passed as an argument.
 Pass by Reference: On passing arguments as pass by reference, the
original value is passed. Therefore, the original value gets altered. In pass
by reference we actually pass the address of the value, where it is stored
using ampersand sign(&)
UNIT III S.A

Example for pass by reference

<!DOCTYPE html>
<html>
<body>

<?php
function add_five(&$value) {
$value += 5;
echo "$value" ."<br>";
}

$num = 2;
add_five($num);
echo $num;
?>

</body>
</html>

In PHP, arguments are usually passed by value, which means that a copy of the
value is used in the function and the variable that was passed into the function
cannot be changed.

When a function argument is passed by reference, changes to the argument also


change the variable that was passed in. To turn a function argument into a
reference, the & operator is used.

You might also like