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

PHP Chapter 1

The document outlines a course on Web Based Application Development using PHP, detailing course and unit outcomes focused on programming with control statements. It covers the history, syntax, features, advantages, and disadvantages of PHP, along with practical examples and explanations of variables, decision-making, and looping statements. Additionally, it provides guidance on running PHP programs using XAMPP and explains the differences between various output methods in PHP.

Uploaded by

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

PHP Chapter 1

The document outlines a course on Web Based Application Development using PHP, detailing course and unit outcomes focused on programming with control statements. It covers the history, syntax, features, advantages, and disadvantages of PHP, along with practical examples and explanations of variables, decision-making, and looping statements. Additionally, it provides guidance on running PHP programs using XAMPP and explains the differences between various output methods in PHP.

Uploaded by

catstudysss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

Program: Information Technology

Course Name: Web Based Application Development using PHP

Course Code: 22619

Course Outcome: Develop Program using control statement

Unit Outcomes: a) Write simple PHP program to solve the given expressions
b)Use relevant decision-making control statements to solve
the given problem.
c)Solve the given iterative problem using relevant loop
statement.
Learning Outcome 2 :
Student should understand basic concepts usen in
PHP
What we
What we willwill
learnlearn
today today

► History and advantages of PHP


► Syntax of PHP
► Variables, Data Types, Expressions and Operators
► Constants
► Decision Statements and Looping statements
Concept Map
PHP

• PHP is a widely used open-source language that is specifically used for web application
development and can be embedded within HTML. PHP is a server-side scripting language
that is used in Web based applications.
• PHP is a general-purpose programming language originally designed for web application
development. PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
• PHP is an open source, server-side programming language.
• PHP is an interpreted language, i.e., there is no need for compilation. PHP files have
extension ".php". 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 is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
Features of PHP

► Web Application Features


► CLI (Command Line Interface)
► Built-in Modules
► Object-Oriented Programming (OOP)
► Pre-Compilation
► Real Time Access Monitoring
► File I/O

5
History of PHP

PHP Version Release Date


1.0 8 June 1995 Officially called "Personal Home Page Tools (PHP Tools)".
Two programmers, Zeev Suraski and Andi Gutmans, rebuilt PHP's
2.0 1 November 1997
core, releasing the updated result as PHP/FI 2 in 1997.
3.0 6 June 1998 first widely used version.
• PHP 4 was released in May 2000, with a new core, known as the
Zend Engine 1.0.
• improved speed and reliability over PHP 3.
4.0 22 May 2000 • PHP 4 added references, the Boolean type, COM support on
Windows, output buffering, many new array functions, expanded
objectoriented programming, inclusion of the PCRE library, and
more
4.1 10 December 2001 Introduced "superglobals" ($_GET, $_POST, $_SESSION, etc.)
Disabled register_globals by default. Data received over the network
4.2 22 April 2002 is not inserted directly into the global namespace anymore, closing
possible security holes in applications.

6
Continues..
PHP Version Release Date
4.3 27 December 2002 Introduced the command-line interface (CLI), to supplement the CGI.
• powered by the new Zend Engine II.
• included new features such as improved support for object-
5.0 13 July 2004 oriented programming, the PHP Data Objects (PDO) extension
(which defines a lightweight and consistent interface for accessing
databases), and numerous performance enhancements.
Performance improvements with introduction of compiler variables
5.1 24 November 2005
in re-engineered PHP Engine.
5.2 2 November 2006 released, with native JSON support.
was released, with Namespace support; late static bindings, jump
label (limitedgoto), closures, PHP archives (phar), garbage collection
for circular references, improved Windows support, sqlite3, mysqlnd
5.3 30 June 2009 as a replacement for libmysql as underlying library for the extensions
that work with MySQL, fileinfo as a replacement for mime_magic for
better MIME support, the Internationalization extension, and
deprecation of ereg extension.

7
Continues..
PHP Version Release Date
• was released with several improvements to existing features,
performance and reduced memory requirements.
5.4 1 March 2012
• Removed items: register_globals, session_register(),
session_unregister().
released, with generators and finally blocks for exceptions handling
5.5 20 June 2013
support.
released which includes features like Constant expressions, Default
5.6 28 August 2014 character encoding, pgsql async support, an interactive debugger
phpdbg and so on.
comes with features like Null coalescing operator, Scalar type
7.0 3 December 2015 declarations, Return type declarations, Spaceship operator and many
more.
was released with features like Nullable types, Asynchronous signal
7.1 1 December 2016 handling, Class constant visibility, Symmetric array destructuring and so
on.

8
Continues..
PHP Version Release Date

was released with features like Abstract method overriding, New


7.2 30 November 2017 object type etc.

was released with features like Abstract method overriding, Parameter


7.3 6 December 2018 type widening, Flexible Heredoc and Nowdoc syntaxes and so on.

offers to build applications that influences everything from the website


7.4 28 November 2019 and mobile to organizations and the cloud.

Just-In-Time (JIT) compilation, arrays starting with a negative index,


8.0 26 November 2020 TypeError on invalid arithmetic/bitwise operators,

9
Advantages of PHP

► Fast
► Open Source
► Platform Independent
► Simple and Easy
► Database
► Support
► Powerful Library Support
► Flexibility

10
Disadvantages of PHP

► Security
► Weak Type
► Not Suitable for Large Web Applications
► Desktop Applications
► Modification Problem

11
Syntax of PHP

► A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
► A PHP script can be placed anywhere in the document.
► A PHP programming script starts with <?php and ends with ?>
<?php
// PHP code goes here…
?>
► The default file extension for PHP files is ".php".
► A PHP file normally contains HTML tags and some PHP scripting code.

12
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".

13
Step to Run Program using XAMPP Server
► XAMPP is a software distribution which provides the Apache web server, MySQL database
(actually
► MariaDB), PHP and Perl (as command-line executables and Apache modules) all in one
package.
► Follow the following steps to run PHP program using XAMPP server:
► Step 1: Download the XAMPP server from the internet
► Step 2: Install the XAMPP software.
► Step 3: Open and click on the start button that is in front of Apache text
Continues..
► Step 4: Create php file in htdocs directory which is resides in xampp directory. [C:\xampp\
htdocs].
► Example: (first.php). The PHP echo statement is often used to output data to the screen.
► <!DOCTYPE html>
► <html>
► <body>
► <h1>My first PHP page</h1>
► <?php
► echo "Hello PHP";
► ?>
► </body>
► </html>
► Step 5: Save first.php in htdocs directory then open your browser and then type
► http://localhost/first.php on address bar and press Enter key.
PHP Comments
► 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 (#).
<?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 (*/),

► <?php
/*
This is a multiple line comment block
that spans across more than
one line
*/
echo "Hello, world!"; ?>
PHP echo and print
► In PHP, there are two ways to get output or print output: echo and print.
► They are both used to output data to the screen.

The PHP echo Statement :


► 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 Output:
Programming";
echo "<br/>";
Hello, Welcome to PHP Programming
//Displaying Strings as Multiple Hello Welcome PHP
arguments
echo "Hello", " Welcome", " PHP"; Hello, PHP
echo "<br/>"; 10+20=30
//Displaying variables
$s="Hello, PHP";
$x=10;
$y=20;
echo "$s <br/>";
echo $x."+".$y."=";
echo $x + $y;
?>
PHP echo and print
The PHP print Statement :
► The PHP print statement is similar to the echo statement and can be used alternative
to echo at many times.
► It is also language construct and so we may not use parenthesis : print or print().
print statement can also be used to print strings and variables.
Example
<?php
// Displaying strings
print "Hello, Welcome to PHP
Programming"; Output:
print "<br/>";
Hello, Welcome to PHP Programming
Hello, PHP
//Displaying variables 10+20=30
$s="Hello, PHP";
$x=10;
$y=20;
print "$s <br/>";
print $x."+".$y."=";
print $x + $y;
?>
Difference between echo and print

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.

Echo is faster than print Print is slower than echo.

Not written with parenthesis. It can or cannot be written with parenthesis.

Syntax: echo($arg1, $arg2, ….) Print ($arg)

Page
21
print_r() function in PHP
• The print_r() function is used to print human-readable information about a variable.
Syntax : print_r( $variable, $isStore )
• $variable : This parameter specifies the variable to be printed and is a mandatory
parameter.
• $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.
Page
22
Example
<?php
// string variable
$var1 = "Hello PHP"; Output:
// integer variable
$var2 = 101; Hello PHP
// array variable 101
$arr = array('0' => "Welcome", '1' => "to", '2' Array ( [0] => Welcome [1] => to [2] =>
=> "PHP"); PHP )
// printing the variables
print_r($var1);
echo "<br/>";
print_r($var2);
echo "<br/>";
print_r($arr);

?>
Variables

►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.
►After declaring a variable it can be reused throughout the code.
►In PHP, a variable starts with the $ sign, followed by the name of the
variable :
►The assignment operator (=) used to assign value to a variable.
►In PHP variable can be declared as : $var_name = value;
<html>
<body>
<?php
// Declaration of variables Output:
$txt = "Hello World!";
$number = 10; Hello World!
// Display variables value 10
echo $txt;
echo "<br>";
echo $number;
?>
</body>
</html>
Rules for Declaring 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. $arg
 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 cannot start with a number.
 A variable name can only contain alpha-numeric characters (0-9A-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.
Variable Scope
►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.
<?php
//the variable $num declare outside this function is
different variable Output:
$num = 20; local num = 10
Variable num outside local_var()
function local_var()
= 20
{
$num = 10;
echo "local num = $num<br/>";
}
local_var();

echo "Variable num outside local_var()=$num<br/>";


?>
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.
<?php
//declare global variable
$num = 20;

function local_var() Output:


{
global $num; Access global variable within function=20
echo "Access global variable within function=$num<br/>";
} globalvariablenum outside of local_var()=20

local_var();

echo "globalvariablenum outside of local_var()=$num<br/>";


?>
3.Static Variables :
 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.
<?php
function static_var()
{
static$x =1;
$y=1; Output:
$x++; x=2
$y++; y=2
echo "x=$x <br/>"; x=3
echo "y=$y <br/>"; y=2
} x=4
y=2
static_var();
static_var();
static_var();
?>
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
►$x represents variables whereas $$x represents a variable with the
content of $x
►$$x = $($x) = $(“Hello”) = $Hello = PHP
►Data stored in $ is fixed while data stored in $$(double dollar sign) can
be changed dynamically.
<?php Output:
$x="Hello";
$$x=”PHP”; Hello
echo $x."<br/>"; PHP
echo $$x."<br/>"; PHP
echo $Hello;
?>
Data Types
 Data types are used to hold different types of data or values.
 PHP supports 8 primitive data types that can be categorized in 3 types :

Scalar Type Compound Type Special Type


Integer Array Resource
Float Object NULL
String
Boolean
Scalar Type (Single value types) :
► There are 4 scalar data types in PHP.
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
(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
<?php
$a=11;
$b=11.22;
$c="Hello PHP"; Output:

$d=True; int(11)
var_dump($a); float(11.22)
string(9) "Hello PHP"
var_dump($b); bool(true)
var_dump($c);
var_dump($d);
?>
2. Compound Type :
► There are 2 compound data types in PHP: Array and object.
(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.
 Syntax : Variable_name = array (element1, element2, element3, element4......)
Example 1:
<?php Example 2:
$intArray = array( 10, 20 , 30); <?php
echo "First Element: $intArray[0] <br/>"; $a = [10, 20, 30, 40];
echo "Second Element: $intArray[1] <br/>"; print_r($a);
echo "Third Element: $intArray[2] <br/>"; ?>
?>

Output:
First Element: 10 Output:
Second Element: 20
Third Element: 30 Array ( [0] => 10 [1] => 20 [2] => 30 [3] => 40 )
Object
► 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).

<?php
class vehicle
{ Output:
function car()
{
echo "City Honda"; City Honda
}
}
$obj1 = new vehicle;
$obj1->car();
?>
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.

<?php
// Open a file for reading
$f1=fopen("note.txt","r");
var_dump($f1);
echo"<br>";

// Connect to MySQL database server with


default setting
$link=mysql_connect("localhost","root","");
var_dump($link);
?>
(ii)Null : Null is a special data type which can have only one value NULL i.e. a variable
that has no value assigned to it. If a variable is created without a value, it is automatically
assigned a value of NULL.
Syntax : $var_name= NULL

<?php
Output:
$x = "Hello world!";
$x = null; NULL
var_dump($x);
?>
Type Casting
► 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.

Cast Operator Conversion


(int) or (integer) Integer
(bool) or (boolean) Boolean
(float) or (double) or (real) Float
(string) String
(array) Array
(object) Object
► PHP provides datatype functions to get or set the datatype of a variable or to check
whether a variable is a particular datatype. Those functions are gettype(), settype().
► gettype() is used to check data type of variable and settype()is used to change a
variables datatype.
<?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
Expressions and Operators
► PHP operators can be classified into a number of categories :
1) Arithmetic Operators
2) Assignment Operators
3) Comparison Operators
4) Increment/Decrement Operators
5) Logical or Relational Operators
6) String Operators
7) Array Operators
8) Conditional or Ternary Operators
9) Spaceship Operators (Introduced in PHP 7)
10) Bitwise Operators
Arithmetic Operators

Operator Description Syntax Operation


+ Addition $a + $b Sum the operands
- Subtraction $a- $b Differences the operands
* Multiplication $a* $b Product of the operands
/ Division $a/ $b Quotient of the operands
** Exponentiation $a** $b $x raised to the power $y
% modulus $a% $b Remainder of the operands

Page
47
<?php
$a = 20;
$b = 10;
echo "First number:$a <br/>";
echo "Second number:$b <br/>"; Output:
echo "<br/>";
$c = $a + $b; First number:20
echo "Addtion: $c <br/>"; Second number:10
$c = $a - $b; Addtion: 30
Substraction: 10
echo "Substraction: $c <br/>";
Multiplication: 200
$c = $a * $b; Division: 2
echo "Multiplication: $c <br/>"; Modulus: 0
$c = $a / $b;
echo "Division: $c <br/>";
$c = $a % $b;
echo "Modulus: $c <br/>";
?> Page
48
Assignment Operators

Operator Description Syntax Operation


= Assign $a = $b Operand on the left obtains the value of
the operand on right

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


-+ Subtract then Assign $a -= $b Simple subtraction same as $a = $a – $b
*= Multiply then Assign $a *= $b Simple product same as $a = $a * $b
/= Divide then Assign $a /= $b Simple division same as $a = $a / $b
(quotient)
%= Divide then Assign $a %= $b Simple division same as $a = $a % $b
(remainder)

Page
49
<?php
$a=20; // simple assign operator
echo "a=$a <br/>";
//add then assign operator
$a+=10;
echo "a=a+10 :$a <br/>";

// subtract then assign operator


$a-=10;
Output:
echo "a=a-10 :$a <br/>";
a=20
// multiply then assign operator a=a+10 : 30
$a*=10; a=a-10 : 20
echo "a=a*10 :$a <br/>"; a=a*10 : 200
a=a/10 : 20
// Divide then assign(quotient) operator a=a%2 : 0
$a/=10;
echo "a=a/10 :$a <br/>";

// Divide then assign(remainder) operator


$a%=2;
echo "a=a%2 :$a <br/>";
?> Page
50
Comparison Operator
Operator Description Syntax Operation
== Equal To $a == $b Returns True if both the operands are equal
!= 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 $a < $b Returns True if $a is less than $b
> Greater Than $a > $b Returns True if $a is greater than $b
<= Less Than or Equal To $a <= $b Returns True if $a is less than or equal to $b
>= Greater Than or Equal $a >= $b Returns True if $a is greater than or equal to $b
To

Page
51
<?php
$a=20;
Output:
$b=10;
$c=20; bool(true)
var_dump($a == $c) + "<br/>"; bool(true)
var_dump($a != $b) + "<br/>"; bool(true)
var_dump($a <> $b) + "<br/>"; bool(true)
var_dump($a === $c) + "<br/>"; bool(false)
var_dump($a !== $c) + "<br/>"; bool(false)
var_dump($a < $b) + "<br/>"; bool(true)
var_dump($a > $b) + "<br/>"; bool(false)
bool(true)
var_dump($a <= $b) + "<br/>";
var_dump($a >= $b);
?>
Page
52
Increment/Decrement Operators

Operator Description Syntax Operation

++ Pre-Increment ++$a First increments $x by one, then return $x

-- Pre-Decrement --$a First decrements $x by one, then return $x

++ Post-Increment $a++ First returns $x, then increment it by one

-- Post-Decrement $a-- First returns $x, then decrement it by one

Page
53
<?php
$a = 3;
echo ++$a, " First increments then prints <br/>"; Output:
$a = 3;
echo $a++, " First prints then increments <br/>"; 4 First increments then prints
$a = 3; 3 First prints then increments
echo --$a, " First decrements then prints <br/>"; 2 First decrements then prints
$a = 3; 3 First prints then decrements
echo $a--, " First prints then decrements <br/>";
?>

Page
54
Logical Operator
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

Page
55
<?php
$a = 20;
$b = 10;
if ($a == 20 and $b == 10)
echo "True <br/>";
Output:
if ($a == 20 or $b == 30)
echo "True <br/>";
True
if ($a == 20 xor $b == 5) True
echo "True <br/>"; True
True
if ($a == 20 && $b == 10) True
echo "True <br/>";

if ($a == 20 || $b == 20)
echo "True <br/>";
?> Page
56
String Operators

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

Page
57
<?php
//first string
$a="Hello";
//second string
$b="World"; Output:
//concatenation of string
$c=$a.$b; HelloWorld
echo "$c <br/>"; HelloPHP
//$a contains HelloPHP
$a.="PHP";
echo "$a";
?>
Page
58
Array Operators

Operator Description Syntax Operation


+ Union $a + $b Union of both i.e., $x and $y

== Equality $a == $b Returns true if both has same key-value pair

!= Inequality $a != $b Returns True if both are unequal

=== 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

<> Inequality $a <> $b Returns True if both are unequal

Page
59
<?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>";
?>
array(4) { ["a"]=> string(1) "c" ["b"]=> string(4) "Perl" ["d"]=> string(4) "Java" ["e"]=> string(6) "Python" }
bool(false)
bool(false)
bool(true)
bool(false)
bool(true) Page
60
Conditional or Ternary Operators
• 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 :
Boolean expression ? operand1: operand2;
• 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.
Page
61
<?php
$a=-10;
Output:
echo ($a> 0) ? 'The number is
positive' : 'The number is negative'; The number is negative
?>

Page
62
Spaceship Operators (Introduced in PHP 7)
• 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.

Page
63
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


Page
64
<?php
$a=30;
$b=30;
$c=20;
Output:
echo $a <=> $b;
echo "<br/>";
0
echo $a <=> $c;
1
echo "<br/>";
-1
echo $c <=> $b;
0
echo "<br/>";
-1
1
// We can do the same for Strings
print("a" <=> "a"); print("<br/>");
print("a" <=> "b"); print("<br/>");
print(“c" <=> "b"); print("<br/>");
?>
Page
65
Bitwise Operators
Operator Description Syntax Operation
& And $a & $b Bits that are set in both $a and $b are set
| Or (inclusive or) $a | $b Bits that are set in either $a or $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 "divide by two")

Page
66
& (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.

<?php
$a=5;
$b=3;
echo $a & $b;
echo "<br/>";
?>

(Binary representation of 5 is 0101 and 3 is 0011. Therefore, their bitwise & will be 0001) Page
67
| (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.

<?php
$a=5;
$b=3;
echo $a | $b;
echo "<br/>";
?>

( Binary representation of 5 is 0101 and 3 is 0011.Therefore their bitwise | will be 0111 )


Page
68
^ (Bitwise XOR )
• This is also known as Exclusive OR operator. Bitwise XOR takes two numbers as
operands and does XOR on every bit of two numbers. The result of XOR is 1 if the
two bits are different.
<?php
$a=5;
$b=3;
echo $a ^ $b;
echo "<br/>";
?>

( Binary representation of 5 is 0101 and 3 is 0011. Therefore their bitwise ^ will be 0110)
Page
69
~ (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.
<?php
$a=5;
echo ~$a;
echo "<br/>";
?>

( Binary representation of 5 is 0101. Therefore the bitwise ~ of this will be 1010 )


Page
70
<< (Bitwise Left Shift)
• Bitwise Left Shift operator takes two numbers, left shifts the bits of the
first operand, the second operand decides the number of places to shift.
<?php
$a=5;
$b=1;
echo $a<<$b;
echo "<br/>";
?>

( Binary representation of 5 is 0101 . Therefore, bitwise << will shift the bits of 5 one times towards the left i.e. 1010 )

Page
71
>> (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.

<?php
$a=5;
$b=1;
echo $a>>$b;
echo "<br/>";
?>

( Binary representation of 5 is 0101 . Therefore, bitwise >> will shift the bits of 5 one times towards the right i.e. 1010)

Page
72
Constants
 A constant is a name or an identifier for a fixed value.
 A constant value cannot change during the execution of the script.
 By convention, constant identifiers are always uppercase.
 By default, a constant is case-sensitive.
 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 Page
73
<?php
// Creates a case-sensitive constant
define("HELLO", "Hello PHP"); Output:
echo HELLO, "<br/>";
// Creates a case-insensitive constant Hello PHP
define("HELLO", "Hello PHP", true); Hello PHP
echo hello;
?>

Page
74
Decision Making Control Statements
• if statement
Syntax :
if(condition)
{
// Code to be executed
}

Page
75
<?php
$a=10;
if ($a > 0) Output:
{ The number is positive
echo "The number is positive";
}
?>

Page
76
if-else Statement
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}

Page
77
<?php
$a=-10;
if ($a > 0)
{ Output:
echo "The number is positive";
}
else The number is negative
{
echo "The number is negative";
}
?>

Page
78
• Nested-if Statement
Syntax :
if(condition1)
{
// Code to be executed if condition1 is true
}
elseif(condition2)
{
// 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 Page
} 79
<?php
$per=65;
if ($per >= 75)
{
echo "Distinction";
}
else if ($per <75 && $per >=60)
{
echo "First Class";
} Output:
else if ($per <60 && $per >= 45)
{
echo "Second Class"; First Class
}
else if ($per <45 && $per >= 40)
{
echo "Pass Class";
}
else
{
echo "Sorry Fail";
}
?> Page
80
Switch Statement
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;
}
Page
81
<?php
$ch=1;
$a=20;
$b=10;
switch ($ch)
{
case 1:
$c=$a + $b;
echo "Addition=".$c;
break;
case 2:
$c=$a - $b;
Output:
echo "Subtraction=".$c;
break;
case 3:
$c=$a * $b;
Addition=30
echo "Multiplication=". $c;
break;
case 4:
$c=$a / $b;
echo "Division=". $c;
break;
default:
echo "Wrong Choice";
}
?> 82
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.

<?php
for($i=1; $i<=5;$i++)
{ Output:
echo "$i<br/>";
if($i==3) 1
{ 2
break; 3
}
}
?> Page
83
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”.

<?php
for($i=1; $i<=5;$i++)
Output:
{
if($i==3) 1
{ 2
continue; 4
} 5
echo "$i<br/>";
}
?>
Page
84
Loop Control Statements
• while Statement
Syntax :
while (if the condition is true)
{
// code is executed
}

Page
85
<?php
Output:
//while loop to print even numbers
$i=0; 0
while ($i<= 10) 2
4
{ 6
echo "$i<br/>"; 8
$i+=2; 10
}
?>

86
• do-while Statement
Syntax :
do
{
//code is executed
} while (if condition is true);

87
<?php
//do-while loop to print odd Output:
numbers
$i=1; 1
do 3
{ 5
7
echo "$i<br/>"; 9
$i+=2;
}while ($i< 10);
?>
88
for Statement
• Syntax :

for (initialization expression; test


condition; update expression)
{
// code to be executed
}

89
<?php Output:
//for loop to print even numbers and
0
sum of them
2
$sum=0; 4
for($i=0; $i<=10;$i+=2) 6
{ 8
echo "$i<br/>"; 10
$sum+=$i; Sum=30
}
echo "Sum=$sum";
?>

90
foreach Statement
• 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:
foreach (array_element as value)
{
//code to be executed
}

91
<?php
Output:
$arr = array (10, 20, 30, 40, 50);
foreach ($arr as $i) 10
20
{ 30
echo "$i<br/>"; 40
50
}
?>

92
Thank You

93
94

You might also like