Unit-I Expressions and control statements in PHP Final_edited
Unit-I Expressions and control statements in PHP Final_edited
Unit-I Expressions and control statements in PHP Final_edited
1 in PHP
UNIT I
Syllabus
1.3 Decision making control statements-if, if-else, nested-if, switch, break and continue statement
1.1 Introduction
PHP stands for Hypertext Preprocessor. PHP is a powerful and widely-used open source server-side scripting language
to write dynamically generated web pages. PHP scripts are executed on the server and the result is sent to the
browser as plain HTML.
PHP can be integrated with the number of popular databases, including MySQL, PostgreSQL, Oracle, Sybase, Informix,
and Microsoft SQL Server.
PHP is an "HTML-embedded scripting language" primarily used for dynamic Web applications.
PHP can be embedded within a normal HTML web pages. That means inside your HTML documents you'll have PHP
statements
PHP takes most of its syntax from C, Java, and Perl. It is an open source technology and runs on most operating
systems and with most Web servers. PHP was written in the C programming language by Rasmus Lerdorf in 1994 for
use in monitoring his online resume and related personal information. For this reason, PHP originally stood for
"Personal Home Page".
PHP files have a file extension of ".php", ".php3", or ".phtml"
PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
PHP can handle forms, i.e. gather data from files, save data to a file, through email you can send data, return data to
the user.
You add, delete, modify elements within your database through PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Web Based Application Development using PHP (MSBTE) 1-2 Expressions and Control Statements in PHP
Open Source : PHP is open source and free of cost, which helps developers to install it quickly and readily available
for use. There are a lot of PHP frameworks and developer can choose any of the frameworks to work. All the features
and tools will be provided to the developer for that framework easily. Open Source means you never need to rely on
the manufacturer to release the next version if something doesn’t work or pay for expensive upgrades.
Platform Independent: PHP is mainly supported by all the operating systems like Windows, Unix, Linux etc. The PHP
based developed web applications can be easily run on any platform. It can be integrated with other programming
language and database easily and there is no requirement of re-development. It helps in saving a lot of effort and
cost.
Simple and Easy : PHP is simple and easy to learn and code. The command functions of PHP can easily learn and
understood. The syntax is simple and flexible to use.
Database : PHP is easily connected with the database and make the connection securely with databases. It has a
built-in module that is used to connect to the database easily. Multiple databases can be integrated with PHP.
Fast : PHP is known as the fastest Programming language as compared to another. PHP applications can be easily
loaded over the slow Internet and data speed.
Support : This advantage of PHP has great online support and community, which helps the new developers to help in
writing the code and developing the web applications. Compatible with servers like IIS and APACHE.
Security : PHP frameworks built-in feature and tools make it easier to protect the web applications from the outer
attacks and security threats.
Maintenance : PHP framework is mainly used to make the web application development easier and maintain the
code automatically. Low development and maintenance cost with very high performance and reliability
Fast Performance : Scripts written in PHP usually execute faster than those written in other scripting languages like
ASP.NET or JSP.
Vast Community : Since PHP is supported by the worldwide community, finding help or documentation for PHP
online is extremely easy. PHP is so popular that it’s quite easy for you to get support on PHP.
Scripting language : A scripting language or script language is a programming language that supports scripts. If code
of programming language can embed with other language or integrate with other language or script called scripting
language. PHP is Scripting language because we can embed PHP code into HTML. PHP is server side language because
PHP requires server to run a code. Code of PHP gets executed on server and result of execution is return to the
browser, that’s why PHP is called script language and server side language.
A PHP script starts with the <?php and ends with the ?> tag.
The PHP delimiter <?php and ?> in the following example simply tells the PHP engine to treat the enclosed code block
as PHP code, rather than simple HTML.
Web Based Application Development using PHP (MSBTE) 1-3 Expressions and Control Statements in PHP
On servers with shorthand support enabled, you can start a scripting block with <? and end with ?>.
Syntax :
<?php
echo ‘Hello world’;
?>
Example :
<html>
<body>
<?php echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of
instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have used the
echo statement to output the text "Hello World".
PHP files are plain text files with .php extension. Inside a PHP file you can write HTML like you do in regular HTML
pages as well as embed PHP codes for server side execution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A Simple PHP File</title>
</head>
<body>
<h1><?php echo "Hello, world!"; ?></h1>
</body>
</html>
The above example shows how you can embed PHP codes within HTML to create well-formed dynamic web pages.
If you view the source code of the resulting web page in your browser, the only difference you will see is the PHP
code <?php echo "Hello, world!"; ?> has been replaced with the output "Hello, world!".
Web Based Application Development using PHP (MSBTE) 1-4 Expressions and Control Statements in PHP
What happened here is? when you run this code the PHP engine executed the instructions between the
<?php … ?> tags and leave rest of the thing as it is. At the end the web server send the final output back to your browser
which is completely in HTML.
Example :
<html>
<body class="page_bg">
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>
Output :
A comment is simply text that is ignored by the PHP engine. The purpose of comments is to make the code more
readable. It may help other developer (or you in the future when you edit the source code) to understand what you were
trying to do with the PHP.
PHP support single-line as well as multi-line comments. To write a single-line comment either start the line with
either two slashes (//) or a hash symbol (#).
Example :
<?php
// This is a single line comment
# This is also a single line comment
echo 'Hello World!';
?>
However to write multi-line comments, start the comment with a slash followed by an asterisk (/*) and end the
comment with an asterisk followed by a slash (*/), like this :
<?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!";
?>
Web Based Application Development using PHP (MSBTE) 1-5 Expressions and Control Statements in PHP
In PHP, there are two ways to get output or print output: echo and print.
The echo statement can be used with or without parentheses : echo or echo().
The echo statement can display anything that can be displayed to the browser, such as string, numbers, variables
values, the results of expressions etc.
Example :
<?php
// Displaying strings
echo "Hello, Welcome to PHP Programming";
echo "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
echo "$s <br/>";
echo $x."+".$y."=";
echo $x + $y;
?>
Output :
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(). print statement can also be used to print
strings and variables.
Web Based Application Development using PHP (MSBTE) 1-6 Expressions and Control Statements in PHP
Example :
<?php
// Displaying strings
print "Hello, Welcome to PHP Programming";
print "<br/>";
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
print "$s <br/>";
print $x."+".$y."=";
print $x + $y;
?>
Output :
Echo print
echo outputs one or more strings or arguments. print output only one string or argument.
echo has no return value. print has a return value of 1 so it can be used in expressions.
$variable : This parameter specifies the variable to be printed and is a mandatory parameter.
Web Based Application Development using PHP (MSBTE) 1-7 Expressions and Control Statements in PHP
$isStore : This an option parameter. This parameter is of boolean type whose default value is FALSE and is used to
store the output of the print_r() function in a variable rather than printing it. If this parameter is set to TRUE then the
print_r() function will return the output which it is supposed to print.
Return Value : If the $variable is an integer or a float or a string the function prints the value of the variable. If the
variable is an array the function prints the array in a format which displays the keys as well as values, a similar
notation is used for objects. If the parameter $isStore is set to TRUE then the print_r() function will return a string
containing the information which it is supposed to print.
Example :
<?php
// string variable
$var1 = "Hello PHP";
// integer variable
$var2 = 101;
// array variable
$arr = array('0' => "Welcome", '1' => "to", '2' => "PHP");
// printing the variables
print_r($var1);
echo "<br/>";
print_r($var2);
echo "<br/>";
print_r($arr);
?>
Output :
Hello PHP
101
Array ( [0] => Welcome [1] => to [2] => PHP )
1.2 Variables
Q. How PHP variables are different from other language’s variables? (2 Marks)
Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a
script.
In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to
the correct data type, depending on its value.
In PHP, a variable starts with the $ sign, followed by the name of the variable :
Web Based Application Development using PHP (MSBTE) 1-8 Expressions and Control Statements in PHP
Example :
<html>
<body>
<?php
// Declaration of variables
$txt = "Hello World!";
$number = 10;
// Display variables value
echo $txt;
echo "<br>";
echo $number;
?>
</body>
</html>
Output :
Hello World!
10
Rules for Declaring PHP Variables :
Q. Write down the rules to know about the variables in PHP? (4 Marks)
A variable starts with the $ sign, followed by the name of the variable.
A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an
underscore ($first_name), or with capitalisation ($firstName).
Variables used before they are assigned have default values.
A variable name can only contain alpha-numeric characters (A-Z, a-z) and underscores.
Variable names are case-sensitive ($name and $NAME are two different variables)
You able to use variable over and over again in your PHP script after declaring it.
Variables can, but do not need, to be declared before assignment. PHP automatically converts the variable to the
correct data type, depending on its value.
Variables in PHP do not have intrinsic types - a variable does not know in advance whether it will be used to store a
number or a string of characters.
Web Based Application Development using PHP (MSBTE) 1-9 Expressions and Control Statements in PHP
In PHP, a variable does not need to be declared before adding a value to it.
For example :
<?php
$str="Hello World!";
$x=16;
?>
In above example, you do not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In a strongly typed programming language, you have to declare (define) the type and name of the variable before
using it.
Scope of a variable is defined as its extent in program within which it 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. There are three different variable scope:
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. Local variables 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
//the variable $num declare outside this function is different variable
$num = 20;
function local_var()
{
$num = 10;
echo "local num = $num<br/>";
}
local_var();
Web Based Application Development using PHP (MSBTE) 1-10 Expressions and Control Statements in PHP
local num = 10
Variable num outside local_var() = 20
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
//declare global variable
$num = 20;
function local_var()
{
global $num;
echo "Access global variable within function=$num<br/>";
}
local_var();
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.
Web Based Application Development using PHP (MSBTE) 1-11 Expressions and Control Statements in PHP
Example :
<?php
function static_var()
{
static $x=1;
$y=1;
$x++;
$y++;
echo "x=$x <br/>";
echo "y=$y <br/>";
}
static_var();
static_var();
static_var();
?>
Output :
x=2
y=2
x=3
y=2
x=4
y=2
Note : $x is regularly increments even after the first function call but $y doesn’t. This is because $y is not static
and it’s memory is freed after execution of first function call.
1.2.2 PHP $ and $$ Variables
The $var (single dollar) is a normal variable with the name var that stores any value like string, integer, float, etc.
Example : $x=”Hello”;
The $$var (double dollar) is a reference variable that stores the value of the $variable inside it (variable of a variable).
Example : $$x=100
Data stored in $ is fixed while data stored in $$(double dollar sign) can be changed dynamically.
Web Based Application Development using PHP (MSBTE) 1-12 Expressions and Control Statements in PHP
Example :
<?php
$x="Hello";
$$x=”PHP”;
echo $x."<br/>";
echo $$x."<br/>";
echo $Hello;
?>
Output :
Hello
PHP
PHP
String
Boolean
(i) Integer : This data type holds only numeric values. Integers hold only whole numbers including positive and negative
numbers, i.e., numbers without fractional part or decimal point. The range of integer values are -2,147,483,648 to
+2,147,483,647. Integers can be defined indecimal(base 10), hexadecimal(base 16), octal(base 8) or binary(base 2)
notation.The default base is decimal (base 10). The octal integers can be declared with leading 0 and the hexadecimal
can be declared with leading 0x. The PHP var_dump() function returns the data type and value.
Decimal Values : Decimal values are represented by a sequence of digits without leading zeros. The sequence may
begin with a plus(+) or minus (-) sign. It considers positive numbers, if no sign is assigned. Example: 50, -11, +33.
Octal Numbers : Octal numbers are represented by leading O and sequence of digits from 0 to 7. Octal numbers can
be prefixed with a plus or minus. Example: O53, +O10
Hexadecimal Values: Hexadecimal values begins with Ox, followed by sequence of digits (0-9) or letters(A-F).
Example: Ox10
Web Based Application Development using PHP (MSBTE) 1-13 Expressions and Control Statements in PHP
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2) notation
(ii) Float : Floating point numbers represents numeric values with decimal points (real numbers) or a number in
exponential form. The range of floating point values are 1.7E-308 to 1.7E+308. Example: 3.14, 0.25, -5.5, 2E-4, 1.2e2
(iii) String : A string is a sequence of characters. A string are declares using single quotes or double quotes. Example:
“Hello PHP”, ‘Hello PHP’
(iv) Boolean : The Boolean data types represents two values, true(1) or false(0). Example: $a=True
Example :
<?php
$a=11;
$b=11.22;
$c="Hello PHP";
$d=True;
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
?>
Output :
int(11)
float(11.22)
string(9) "Hello PHP"
bool(true)
2. Compound Type :
(i) Array: An array stores multiple values in one single variable and each value is identify by position ( zero is the first
position). The array is a collection of heterogeneous (dissimilar) data types. PHP is a loosely typed language that’s
why we can store any type of values in arrays.
Example 1:
<?php
$intArray = array( 10, 20 , 30);
echo "First Element: $intArray[0] <br/>";
echo "Second Element: $intArray[1] <br/>";
echo "Third Element: $intArray[2] <br/>";
?>
Output :
First Element: 10
Second Element: 20
Third Element: 30
Example 2 :
<?php
$a = [10, 20, 30, 40];
print_r($a);
?>
Output :
Objects are defined as instances of user defined classes that can hold both values and functions. First we declare class
of object using keyword class. A class is a structure that contain properties(variables) and methods(functions).
Example :
<?php
class vehicle
{
function car()
{
echo "City Honda";
}
}
$obj1 = new vehicle;
$obj1->car();
?>
Web Based Application Development using PHP (MSBTE) 1-15 Expressions and Control Statements in PHP
Output :
City Honda
3. Special Type
(i) Resource : The special resource type is not an actual data type. It is the storing of a reference to functions and
resources external to PHP. Consider a function which connect to the database, a function to send a query to the
database, a function to close the connection of database. Resource variables hold special handles to opened files,
database connections, streams etc.
Example :
<?php
// Open a file for reading
$f1=fopen("note.txt","r");
var_dump($f1);
echo"<br>";
Example :
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output :
NULL
Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is
used. If an integer value is assigned to a variable, it becomes an integer. If a string value is assigned to variable, it
becomes a string.
PHP does not require (or it support) explicit type definition in variable declaration; a variable’s type is determined by
the context in which the variable is used.
PHP variable types may be modified without any explicit conversion process. This conversion process, whether
explicit or implicit, is known as type juggling.
Example
Typecasting is a way to convert one data type variable into the different data type. A type can be cast by inserting
one of the casts in front of the variable.
(string) String
(array) Array
(object) Object
Example :
gettype() is used to check data type of variable and settype()is used to change a variables datatype.
Web Based Application Development using PHP (MSBTE) 1-17 Expressions and Control Statements in PHP
Example:
<?php
$count = "5";
echo gettype($count); // before datatype conversion: $count is a string
settype($count,'int');
echo gettype($count); // after datatype conversion: $count is an integer
?>
Output :
String
integer
Operators are symbols used to manipulate data stored in variables. A value operated on by an operator is referred
to as an operand. The combination of operands with an operator to produce a result is called an expression.
For Example : (1 + 2) Here integer value 1 and 2 are operands and + is the addition operator, operates on operands
to produce the integer result 3.
In PHP, operators are used to perform many operations on variables or operands or values. These operators are
nothing but symbols needed to perform operations of various types. PHP operators can be classified into a number of
categories :
Arithmetic Operators
Assignment Operators
Comparison Operators
Increment/Decrement Operators
String Operators
Array Operators
Arithmetic operators are used in mathematical expression in the same way like addition, subtraction,
multiplication etc, that they are used in algebra.
Web Based Application Development using PHP (MSBTE) 1-18 Expressions and Control Statements in PHP
Example :
<?php
$a = 20;
$b = 10;
echo "First number:$a <br/>";
echo "Second number:$b <br/>";
echo "<br/>";
$c = $a + $b;
echo "Addtion: $c <br/>";
$c = $a - $b;
echo "Substraction: $c <br/>";
$c = $a * $b;
echo "Multiplication: $c <br/>";
$c = $a / $b;
echo "Division: $c <br/>";
$c = $a % $b;
echo "Modulus: $c <br/>";
?>
Output :
First number:20
Second number:10
Addtion: 30
Substraction: 10
Multiplication: 200
Division: 2
Modulus: 0
Web Based Application Development using PHP (MSBTE) 1-19 Expressions and Control Statements in PHP
Example :
<?php
$a=20; // simple assign operator
echo "a=$a <br/>";
//add then assign operator
$a+=10;
echo "a=a+10 :$a <br/>";
Output :
a=20
a=a+10 : 30
a=a-10 : 20
a=a*10 : 200
a=a/10 : 20
a=a%2 : 0
These operators are used to compare two operands and outputs the result in Boolean form. The result is always
either true, if the comparison is truthful, or false, otherwise.
!= Not Equal To $a != $b Returns True if both the operands are not equal
<> Not Equal To $a<> $b Returns True if both the operands are unequal
=== Identical $a === $b Returns True if both the operands are equal and are of
the same type
!== Not Identical $a == $b Returns True if both the operands are unequal and are
of different types
<= Less Than or Equal To $a <= $b Returns True if $a is less than or equal to $b
>= Greater Than or Equal To $a >= $b Returns True if $a is greater than or equal to $b
Example :
<?php
$a=20;
$b=10;
$c=20;
var_dump($a == $c) + "<br/>";
var_dump($a != $b) + "<br/>";
var_dump($a <> $b) + "<br/>";
var_dump($a === $c) + "<br/>";
var_dump($a !== $c) + "<br/>";
var_dump($a < $b) + "<br/>";
var_dump($a > $b) + "<br/>";
var_dump($a <= $b) + "<br/>";
Web Based Application Development using PHP (MSBTE) 1-21 Expressions and Control Statements in PHP
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(true)
bool(false)
bool(true)
Increment operators are called the unary operators as it work on single operands.
The operator ++ adds one to the operand and -- subtract one from the operand.
The x++ and ++x means the same thing when they form statements independently; they behave differently when
they are used in expressions on the right hand side of an assignment statement.
Initial value of x Expression Final value of y Final value of x
3 y=x++ 3 4
3 y=++x 4 4
3 y=x-- 3 2
3 y=--x 2 2
Example :
<?php
$a = 3;
echo ++$a, " First increments then prints <br/>";
$a = 3;
echo $a++, " First prints then increments <br/>";
$a = 3;
echo --$a, " First decrements then prints <br/>";
Web Based Application Development using PHP (MSBTE) 1-22 Expressions and Control Statements in PHP
$a = 3;
echo $a--, " First prints then decrements <br/>";
?>
Output:
Logical operators are basically used to operate with conditional statements and expressions. Conditional statements
are based on conditions. Conditional statement can either be true or false.
Operator Description Syntax Operation
and Logical AND $a and $b True if both the operands are true else false
or Logical OR $a or $b True if either of the operand is true else false
xor Logical XOR $a xor $b True if either of the operand is true and false if both are
true
&& Logical AND $a && $b True if both the operands are true else false
|| Logical OR $a || $b True if either of the operand is true else false
! Logical NOT !$a True if $a is false
Example :
<?php
$a = 20;
$b = 10;
if ($a == 20 and $b == 10)
echo "True <br/>";
if ($a == 20 or $b == 30)
echo "True <br/>";
if ($a == 20 xor $b == 5)
echo "True <br/>";
if ($a == 20 || $b == 20)
echo "True <br/>";
?>
Output :
True
True
True
True
True
There are two string operators. The first is the concatenation operator (‘.‘), which returns the concatenation of Two
strings i.e join right and left arguments. The second is the concatenating assignment operator (‘.=‘), which appends the
argument on the right side to the argument on the left side.
Operator Description Syntax Operation
. Concatenation $a.$b Concatenated $a and $b
.= Concatenation and assignment $a.=$b First concatenates then assigns, same as $a = $a.$b
Example :
<?php
//first string
$a="Hello";
//second string
$b="World";
//concatenation of string
$c=$a.$b;
echo "$c <br/>";
//$a contains HelloPHP
$a.="PHP";
echo "$a";
?>
Output :
HelloWorld
HelloPHP
Web Based Application Development using PHP (MSBTE) 1-24 Expressions and Control Statements in PHP
We can perform operations on arrays using Arrays Operators like Union, Equality, Identity, Inequality and
Non-identity. Assume $a and $b are arrays.
=== Identity $a === $b Returns True if both has same key-value pair in the same
order and of same type
!== Non-Identity $a !== $b Returns True if both are not identical to each other
Example :
<?php
$a = array("a"=>"c","b"=>"Perl");
$b = array("d"=>"Java","e"=>"Python");
var_dump($a + $b);
var_dump($a == $b) + "<br/>";
var_dump($a != $b) + "<br/>";
var_dump($a <> $b) + "<br/>";
var_dump($a === $b) + "<br>";
var_dump($a !== $b) + "<br>";
?>
Output :
array(4) { ["a"]=> string(1) "c" ["b"]=> string(4) "Perl" ["d"]=> string(4) "Java" ["e"]=> string(6) "Python" }
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
The goal of the operator is to decide which value should be assigned to the variable. Ternary operator "?:" basically is
used for an if-then-else as shorthand as :
First expression is evaluated. If expression is true then returns operand1; otherwise returns operand2, if the
expression is false.
For example : x = (y>z) ? y : z
X is assigned the value of y if y is greater than z, else x is assigned the value of z.
Fig. 1.2.1
Example :
<?php
$a=-10;
echo ($a> 0) ? 'The number is positive' : 'The number is negative';
?>
Output :
PHP 7 has introduced a new kind of operator called spaceship operator (). These operators are used to compare
values but instead of returning Boolean result, it returns integer values. It returns -1, 0 or 1. If both the operands are equal,
it returns 0. If the right operand is greater, it returns -1. If the left operand is greater, it returns 1.
Operator Syntax Description
$a< $b $a<=> $b Identical to -1 (right is greater)
$a> $b $a<=> $b Identical to 1 (left is greater)
$a<= $b $a<=> $b Identical to -1 (right is greater) or identical to 0 (if both are equal)
$a>= $b $a<=> $b Identical to 1 (if left is greater) or identical to 0 (if both are equal)
$a == $b $a<=> $b Identical to 0 (both are equal)
$a != $b $a<=> $b Not Identical to 0
Example :
<?php
Web Based Application Development using PHP (MSBTE) 1-26 Expressions and Control Statements in PHP
$a=30;
$b=30;
$c=20;
echo $a <=> $b;
echo "<br/>";
echo $a <=> $c;
echo "<br/>";
echo $c <=> $b;
echo "<br/>";
0
1
-1
0
-1
1
& And $a & $b Bits that are set in both $a and $b are set
^ Xor (exclusive or) $a ^ $b Bits that are set in $a or $b but not both are set.
~ Not ~ $a Bits that are set in $a are not set, and vice versa.
<< Shift left $a << $b Shift the bits of $a$b steps to the left (each step means
"multiply by two")
>> Shift right $a >> $b Shift the bits of $a$b steps to the right (each step means
Web Based Application Development using PHP (MSBTE) 1-27 Expressions and Control Statements in PHP
1. & (Bitwise AND) : This binary operator works on two operands. Bitwise AND operator in PHP takes two numbers as
operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.
Example :
<?php
$a=5;
$b=3;
echo $a & $b;
echo "<br/>";
?>
Output : 1
(Binary representation of 5 is 0101 and 3 is 0011. Therefore, their bitwise & will be 0001)
2. | (Bitwise OR) :Bitwise OR operator takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
Example :
<?php
$a=5;
$b=3;
echo $a | $b;
echo "<br/>";
?>
Output : 7
Example :
<?php
$a=5;
$b=3;
echo $a ^ $b;
echo "<br/>";
?>
Web Based Application Development using PHP (MSBTE) 1-28 Expressions and Control Statements in PHP
Output : 6
( Binary representation of 5 is 0101 and 3 is 0011. Therefore their bitwise ^ will be 0110)
4. ~ (Bitwise NOT) : This is a unary operator i.e. works on only one operand. Bitwise NOT operator takes one number
and inverts all bits of it.
Example :
<?php
$a=5;
echo ~$a;
echo "<br/>";
?>
Output : 6
Example:
<?php
$a=5;
$b=1;
echo $a<<$b;
echo "<br/>";
?>
Output : 10
( Binary representation of 5 is 0101 . Therefore, bitwise << will shift the bits of 5 one times towards the left i.e.
01010 )
6. >> (Bitwise Right Shift) :Bitwise Right Shift operator takes two numbers, right shifts the bits of the first operand, the
second operand decides the number of places to shift.
Example :
<?php
$a=5;
$b=1;
echo $a>>$b;
echo "<br/>";
?>
Output : 2
Web Based Application Development using PHP (MSBTE) 1-29 Expressions and Control Statements in PHP
( Binary representation of 5 is 0101 . Therefore, bitwise >> will shift the bits of 5 one times towards the right i.e.
010)
Operator Precedence: The precedence of an operator specifies how "tightly" it binds two expressions together.
Operators have a set precedence, or order, in which they are evaluated. For example, in the expression 10 + 5 * 2, the
answer is 20 and not 30 because the multiplication * operator has a higher precedence than the addition + operator.
Parentheses () may be used to force precedence, if necessary. For instance: (10 + 5) * 2 evaluates to 30.
Operator Associativity :
When operators have equal precedence their associativity decides how the operators are grouped.
Example :
Associativity Operators
Highest Precedence
n/a ()
n/a new
right []
left */%
left +-.
left &
left ^
left |
left &&
left ||
left ? :
right print
Web Based Application Development using PHP (MSBTE) 1-30 Expressions and Control Statements in PHP
Associativity Operators
left and
left xor
left or
left ,
Lowest Precedence
Example :
<?php
$n1 = 10;
$n2 = 5;
$n3 = 2;
10 + 5 * 2 = 20
(10 + 5) * 2 = 30
1.2.5 Constants
Q. How can we declare variable and constant in PHP? Explain it with an example. (4 Marks)
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.
Common examples of such data include configuration settings such as database username and password, website's
base URL, company name, etc.
The define() function in PHP is used to create a constant
Syntax : define(name, value, case-insensitive)
name : Specifies the name of the constant, value: Specifies the value of the constant, case-insensitive: Specifies
whether the constant name should be case-insensitive. Default is false.
Example :
<?php
// Creates a case-sensitive constant
define("HELLO", "Hello PHP");
echo HELLO, "<br/>";
// Creates a case-insensitive constant
define("HELLO", "Hello PHP", true);
echo hello;
?>
Output :
Hello PHP
Hello PHP
Q. State any four decision making statement along with their syntax in PHP (4 Marks)
Generally instructions are executed sequentially. In some cases it is necessary to change the sequence of executions
based on certain conditions. For this purpose decision control structure is required.
1.3.1 if statement
The if statement is used to execute a block of code only if the specified condition evaluates to true.
if(condition)
Web Based Application Development using PHP (MSBTE) 1-32 Expressions and Control Statements in PHP
{
// Code to be executed
}
Fig. 1.3.1
Example :
<?php
$a=10;
if ($a > 0)
{
echo "The number is positive";
}
?>
Output :
If...else statement first checks the condition. If condition is true, then true statement block is executed. If condition
is false, then false statement block is executed.
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
Web Based Application Development using PHP (MSBTE) 1-33 Expressions and Control Statements in PHP
Fig. 1.3.2
Example :
<?php
$a=-10;
if ($a > 0)
{
echo "The number is positive";
}
else
{
echo "The number is negative";
}
?>
Output :
Nested if statements mean an if block inside another if block. Nested if else statement used when we have more
than two conditions. It is also called if else if statement.
if(condition1)
{
// Code to be executed if condition1 is true
}
elseif(condition2)
Web Based Application Development using PHP (MSBTE) 1-34 Expressions and Control Statements in PHP
{
// Code to be executed if the condition1 is false
and condition2 is true
}
else
{
// Code to be executed if both condition1 and
condition2 are false
}
Fig. 1.3.3
Example :
<?php
$per=65;
if ($per >= 75)
{
echo "Distinction";
}
else if ($per <75 && $per >=60)
{
echo "First Class";
}
else if ($per <60 && $per >= 45)
{
echo "Second Class";
}
else if ($per <45 && $per >= 40)
{
echo "Pass Class";
Web Based Application Development using PHP (MSBTE) 1-35 Expressions and Control Statements in PHP
}
else
{
echo "Sorry Fail";
}
?>
Output :
First Class
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The
switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code
corresponding to that match. The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax :
switch(n)
{
case statement1:
//code to be executed if n==statement1;
break;
case statement2:
//code to be executed if n==statement2;
break;
case statement3:
//code to be executed if n==statement3;
break;
case statement4:
//code to be executed if n==statement4;
break;
......
default:
//code to be executed if n != any case;
} Fig. 1.3.4
Example :
Web Based Application Development using PHP (MSBTE) 1-36 Expressions and Control Statements in PHP
<?php
$ch=1;
$a=20;
$b=10;
switch ($ch)
{
case 1:
$c=$a + $b;
echo "Addition=".$c;
break;
case 2:
$c=$a - $b;
echo "Subtraction=".$c;
break;
case 3:
$c=$a * $b;
echo "Multiplication=". $c;
break;
case 4:
$c=$a / $b;
echo "Division=". $c;
break;
default:
echo "Wrong Choice";
}
?>
Output :
Addition=30
There are two special statements that can be used inside loops:
Web Based Application Development using PHP (MSBTE) 1-37 Expressions and Control Statements in PHP
1. Break : The keyword break ends execution of the current for, for each, while, do while or switch structure. When the
keyword break executed inside a loop the control automatically passes to the first statement outside the loop. A
break is usually associated with the if.
Example :
<?php
for($i=1; $i<=5;$i++)
{
echo "$i<br/>";
if($i==3)
{
break;
}
}
?>
Output :
1
2
3
2. Continue : It is used to stop processing the current block of code in the loop and goes to the next iteration. It is used
to skip a part of the body of the loop under certain conditions. It causes the loop to be continued with the next
iteration after skipping any statement in between. The continue statement tells the compiler ”SKIP THE FOLLOWING
STATEMENTS AND CONTINUE WITH THE NEXT ITERATION”.
Example :
<?php
for($i=1; $i<=5;$i++)
{
if($i==3)
{
continue;
}
echo "$i<br/>";
}
?>
Output :
Web Based Application Development using PHP (MSBTE) 1-38 Expressions and Control Statements in PHP
1
2
4
5
A loop causes a section of a program to be repeated a certain number of times. The repetition continues while the
condition set for it remains true. When the condition becomes false, the loop ends and the control is passed to the
statement following the loop. loop in PHP is used to execute a statement or a block of statements, multiple times until and
unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times.
PHP supports four different types of loops: while, do-while, for and for each.
The while statement will execute a block of code if and as long as a test condition is true. The while is an entry
controlled loop statement. i.e., it first checks the condition at the start of the loop and if its true then it enters the loop and
executes the block of statements, and goes on executing it as long as the condition holds true.
Fig. 1.4.1
Example :
<?php
//while loop to print even numbers
$i=0;
Web Based Application Development using PHP (MSBTE) 1-39 Expressions and Control Statements in PHP
0
2
4
6
8
10
This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the
condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program
is executed as long as the condition holds true.
do
{
//code is executed
} while (if condition is true);
Fig. 1.4.2
Example :
Web Based Application Development using PHP (MSBTE) 1-40 Expressions and Control Statements in PHP
<?php
//do-while loop to print odd numbers
$i=1;
do
{
echo "$i<br/>";
$i+=2;
}while ($i< 10);
?>
Output :
1
3
5
7
9
The for statement is used when you know how many times you want to execute a statement or a block of
statements. That is, the number of iterations is known beforehand. These type of loops are also known as entry-controlled
loops. There are three main parameters to the code, namely the initialization, the test condition and the counter.
In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check
whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop
variable gets updated. Steps are repeated till exit condition comes.
1. Initialization Expression : In this expression we have to initialize the loop counter to some value. for example: $i=1;
2. Test Expression : In this expression we have to test the condition. If the condition evaluates to true then we will
execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $i<=10;
3. Update Expression : After executing loop body this expression increments/decrements the loop variable by some
value. for example : $i+= 2;
Fig. 1.4.3
Example :
<?php
//for loop to print even numbers and sum of them
$sum=0;
for($i=0; $i<=10;$i+=2)
{
echo "$i<br/>";
$sum+=$i;
}
echo "Sum=$sum";
?>
Output :
0
2
4
6
8
10
Sum=30
Web Based Application Development using PHP (MSBTE) 1-42 Expressions and Control Statements in PHP
foreach loop is used for array and objects. For every counter of loop, an array element is assigned and the next
counter is shifted to the next element.
Syntax :
<?php
$arr = array (10, 20, 30, 40, 50);
foreach ($arr as $i)
{
echo "$i<br/>";
}
?>
Output :
10
20
30
40
50
Programs :
Welcome to PHP
2. Write a program in PHP to calculate Square Root of a number.
Web Based Application Development using PHP (MSBTE) 1-43 Expressions and Control Statements in PHP
<?php
function my_sqrt($n)
{
$x = $n;
$y = 1;
while($x > $y)
{
$x = ($x + $y)/2;
$y = $n/$x;
}
return $x;
}
print_r(my_sqrt(16)."<br/>");
print_r(my_sqrt(144)."<br/>");
?>
Output :
4
12
Factorial of 4 is 24
$n2 = 1;
echo "<h3>Fibonacci series for first 12 numbers: </h3>";
echo "\n";
echo $n1.' '.$n2.' ';
while ($num<10 )
{
$n3 = $n2 + $n1;
echo $n3.' ';
$n1 = $n2;
$n2 = $n3;
$num = $num + 1;
}
?>
Output :
}
$number=$number+1;
}
?>
Output :
2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 ,
Output :
8. Write PHP program to print even numbers upto 10 and sum of them
<?php
$sum=0;
for($i=0;$i<=10;$i+=2)
{
echo "$i<br/>";
$sum=$sum+$i;
}
echo "Sum: $sum";
?>
Output :
0
2
4
6
8
10
Sum : 30
9. Write a program to find average of first ten natural numbers using for loop.
<?php
$sum=0;
for ($i=1; $i<=10; $i++)
{
echo "$i<br/>";
$sum=$sum+$i;
}
echo "sum=$sum <br/>";
$average=(float)$sum/$i;
echo "Average=$average"
?>
Web Based Application Development using PHP (MSBTE) 1-47 Expressions and Control Statements in PHP
Output :
1
2
3
4
5
6
7
8
9
10
sum=55
Average=5
Review Questions
Q, 1. Which tag is used to define PHP code?
Q, 14. How do you convert one variable type to another (say, a string to a number)?
Q, 17. “Whole PHP code (script) is case sensitive”. Justify true or false.