0% found this document useful (0 votes)
29 views89 pages

PHP Expressions & Control Statements

PHP, or Hypertext Preprocessor, is an open-source server-side scripting language used for dynamic web applications and e-commerce. It supports various data types, including strings, integers, and arrays, and allows for file manipulation, form data collection, and database interaction. PHP is easy to learn, platform-independent, and has a large community for support and resources.

Uploaded by

pagareankita29
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)
29 views89 pages

PHP Expressions & Control Statements

PHP, or Hypertext Preprocessor, is an open-source server-side scripting language used for dynamic web applications and e-commerce. It supports various data types, including strings, integers, and arrays, and allows for file manipulation, form data collection, and database interaction. PHP is easy to learn, platform-independent, and has a large community for support and resources.

Uploaded by

pagareankita29
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/ 89

UNIT 1

Expressions and Control statements in PHP


What is PHP?

• PHP stands for Hypertext Preprocessor


• PHP is a widely-used, open source ,server side scripting language used for
creating dynamic and interactive web applications and e-commerce platforms
• PHP is free to download and use
What is a PHP File?
• PHP files can contain text, HTML, CSS, JavaScript, and PHP code
• PHP code is executed on the server, and the result is sent to the browser as plain
HTML
• PHP files have extension ".php"
Uses of PHP
• PHP can generate dynamic page content
• PHP can create, open, read, write, delete, and close files on the server
• PHP can collect form data
• PHP can send and receive cookies
• PHP can send and receive emails
• PHP can add, delete, modify data in your database
• PHP can be used to control user-access
• PHP can encrypt data
Why PHP?
• PHP runs on various platforms (Windows, Linux, Unix, Mac OS, etc)
• PHP is compatible with almost all web servers used today (Apache,
IIS,WAMP,XAMPP,etc)
• PHP supports a wide range of databases(such as Oracle, Microsoft SQL
Server,MySQL,PostgreSQL,Sybase,Informix, etc)
• PHP is free. Download it from the official PHP resource: www.php.net
• PHP is easy to learn and runs efficiently on the server side
History of PHP
• PHP was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and
released in 1995. The PHP reference implementation is now produced by the PHP Group.PHP
was originally an abbreviation of Personal Home Page,but it now stands for the recursive
acronym PHP: Hypertext Preprocessor

• PHP is implemented in C and C++.Initially Ramsus Lerdorf wrote PHP to maintain his personal
home page later extended it to communicate with data bases, file systems and work with web
forms and called this implementation as PHP/FI (Personal Home Page/ Forms Interpreter).
• PHP 3 (1998): The first version considered suitable for widespread use.
• PHP 4 (2000): Improved performance and the introduction of the Zend Engine.
• PHP 5 (2004): Added object-oriented programming features.
• PHP 7 (2015): Significant performance improvements and reduced memory usage.
• PHP 8 (2020): Introduction of Just-In-Time (JIT) compilation, further enhancing performance.
Advantages of PHP

1. Open-Source- It is an open-source which means it is free to download and use.


2. Platform Independent- PHP-based applications can run on any OS like UNIX, Linux, Windows,
etc.
3. Easy to learn: PHP has a syntax similar to C and Java, and is easy to learn and use
4. Database support: PHP supports many databases, including MySQL, Oracle, and Microsoft SQL
server,etc
5. Fast Performance: scripts written in PHP executed faster than those written in other scripting
languages such as ASP and JSP. PHP uses its own memory, so the loading time and server
workload automatically get reduced. This results in better PHP performance and faster processing
speed.
6. Community support:PHP has a large and active community of developers who contribute to its
rapid development and continuous improvement
7. Library support:PHP has a collection of prewritten codes that users can repeatedly use whenever
required to optimize the program
Applications of PHP
• Content Management System.
• Web-based applications and development of sites.
• E-commerce websites and applications.
• Data Analytics and Representation.
• Image Processing
• Graphical Interface Design
• General-Purpose Website Development
Basic PHP Syntax

• A PHP script can be placed anywhere in the document.


• A PHP script starts with <?php and ends with ?>

<?php
// PHP code goes here
?>
PHP Example
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!”;
?>
</body>
</html>
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting code.
• PHP statements end with a semicolon (;)
Comments in PHP
• A comment in PHP code is a line that is not executed as a part of the program.
• Comments can be used to:
• Let others understand your code
• Remind yourself of what you did
• Prevent blocks of code from being executed
• Syntax for comments in PHP code:
// This is a single-line comment

# This is also a single-line comment

/* This is a
multi-line comment */
Comments in the Middle of the Code
<?php
$x = 5 /* + 15 */ + 5;
echo $x;
?>
Output:
10
PHP variables
• Variables are "containers" for storing information.
• Creating (Declaring) PHP Variables
• In PHP, a variable starts with the $ sign, followed by the name of the variable.
• A variable can have a short name (like $x and $y) or a more descriptive name ($age,
$total_volume)
• The assignment operator (=) used to assign value to a variable
• In PHP variable can be declared as : $variable_name=value;
• In PHP, there is no need to define data type of the variable
• PHP automatically associates a data type to the variable, depending on its value that’s why PHP is
a Loosely Typed Language

• Example:
<?php Output:
$x =5; // $x is an integer variable 5
$y =10.5; // $y is a float variable 10.5
$z ="Hello world!"; // $z is a string variable Hello world!
$a=$b="Fruit"; //Assign the same value to multiple variables in one line Fruit
echo $x ."<br>"; Fruit
echo $y ."<br>";
echo $z ."<br>";
echo $a ."<br>";
echo $b ."<br>";
?>
Rules for PHP variables
1. A variable starts with the $ sign, followed by the name of the variable
2. A variable name must start with a letter or the underscore character
3. A variable name cannot start with a number
4. A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ )
5. Variable names are case-sensitive ($age and $AGE are two different variables)
6. 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).
• Remember that PHP variable names are case-sensitive !
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can be
referenced/used.
• PHP has three different variable scopes:
• local
• global
• static
Local Scope
• A variable declared within a function has a LOCAL SCOPE and can only be
accessed within that function
• Example:
<?php
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();

echo "<br>Variable x outside function is: $x";


?>
• Output:
Variable x inside function is: 5
Variable x outside function is:
Global Scope
• A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a
function
• Example:
<?php
$x = 5; // global scope
function myTest()
{
echo "Variable x inside function is: $x";
}

myTest();
echo "Variable x outside function is: $x";
?>

• Output:
Variable x inside function is:
Variable x outside function is: 5
PHP The global Keyword
• The global keyword is used to access a global variable within a function.

Example:
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest(); // run function


echo $y; // output the new value for variable $y
?>
Output:
15
Static Scope
• Normally, when a function is completed/executed, all of its variables are deleted.
• However, sometimes we want a local variable NOT to be deleted. We need it for a further job.
• To do this, use the static keyword when you first declare the variable

Example:
<?php
function myTest()
{
static $x = 1;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?>
Output:
1
2
3
PHP Case Sensitivity
• PHP is partially case-sensitive, meaning that
• In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are not
case-sensitive.
• However all variable names are case-sensitive "$color" and "$COLOR" would be considered different
variables in PHP

• All three echo statements below are equal and legal.

Example:

<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>

Output:
Hello World!
Hello World!
PHP Case Sensitivity
Example:

• The only the first statement will display the value of the $color variable.
• This is because $color, $COLOR, and $coLOR are treated as three different variables

<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>

Output:
My car is red
My house is
My boat is
PHP echo and print Statements
• With PHP, there are two basic ways to get output: echo and print.
• echo and print are more or less the same. They are both used to output data to the screen.
• The echo and print statement can be used with or without parentheses
• The differences are small:
Echo Print
Echo has no return value Print has a return value of 1, so it can be
used in expressions
Echo can take multiple parameters Print can take one parameter
Echo is marginally faster than print. Print is slower than echo
Syntax: echo($arg1,$arg2,…) Syntax: print ($arg)

Example: Example:
<?php <?php
echo "Hello world!<br>"; print "Hello world!<br>";
echo "This ", "string ", "was ", "made ", print "This string was made with single
"with multiple parameters."; parameter.";
?> ?>
PHP echo and print Statements
Example:
<?php
//The echo statement can be used with or without parentheses
echo ("Hello world <br>");
echo "Hello world <br>";

$txt1 = "W3Schools.com";
echo "Study PHP at $txt1 <br>"; //using double quotes, variables can be inserted to the string
echo 'Study PHP at ‘ . $txt1; // using single quotes, variables have to be inserted using the . operator

?>
Output:
Hello world
Hello world
Study PHP at W3Schools.com
Study PHP at W3Schools.com
PHP program that performs sum of two numbers

Example:
<?php
$x = 3;
$y = 2;
echo $x + $y;
?>
• Output:
5
How to output text and variables with the echo statements
Example:
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

echo "<h2>" . $txt1 . "</h2>";


echo "Study PHP at " . $txt2 . "<br>";
echo ("Addition is:". ($x + $y));
?>
Output:
Learn PHP
Study PHP at W3Schools.com
Addition is:9
PHP Data Types
• In PHP, data types defines what type of data value a variable can store.
• PHP is a loosely typed language, which means we do not need to declare a variable with specific
data type. PHP automatically associates a data type to the variable, depending on its value
• Variables can store data of different types
• PHP supports the following data types:
• Predefined or scalar Data types
1. String
2. Integer
3. Float (floating point numbers - also called double)
4. Boolean
• User defined or Composite Data types
1. Array
2. Object
• Special Data Types
1. NULL
2. Resource
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double quotes

Example:

<?php
$x = "Hello world!"; //string variable
$y = 'Hello world!';

var_dump($x); //returns the data type and value of variable


echo "<br>";
var_dump($y);
?>

Output:
string(12) "Hello world!"
string(12) "Hello world!"
PHP Integer
• An integer are whole numbers, without a decimal point, like 100.
• Rules for integers:
• An integer must have at least one digit
• An integer must not have a decimal point
• An integer can be either positive or negative

• In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:
• Example:
<?php
$x = 5985; //integer variable
var_dump($x); //returns the data type and value of variable
?>
• Output :
int(5985)
PHP Float
• A float (floating point number) is a number with a decimal point or a number like
3.14 or 49.1.
• In the following example $x is a float. The PHP var_dump() function returns the
data type and value:
• Example
<?php
$x = 10.365; //float variable
var_dump($x);
?>
• Output :
float(10.365)
PHP Boolean
• A Boolean represents two possible states: TRUE or FALSE.
• Booleans are often used in conditional testing.

• Example:
<?php
$x = true;
var_dump($x);
?>
• Output:
bool(true)
PHP Array

• An array stores multiple values in one single variable.


• In the following example $cars is an array.
• The PHP var_dump() function returns the data type and value:
• Example
<?php
$cars = array("Volvo", "BMW", "Toyota"); //indexed array
var_dump($cars);
?>
• Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
• Classes and objects are the two main aspects of object-oriented programming.
• A class is a template for objects, and an object is an instance of a class.
• When the individual objects are created, they inherit all the properties and behaviors from
the class, but each object will have different values for the properties.
• Let's assume we have a class named Car. A Car can have properties like model, color, etc.
We can define variables like $model, $color, and so on, to hold the values of these
properties.
• When the individual objects (Volvo, BMW, Toyota, etc.) are created, they inherit all the
properties and behaviors from the class, but each object will have different values for the
properties.
• If you create a __construct() function, PHP will automatically call this function when you
create an object from a class.
PHP Object
Example
<?php
class Car
{
public $color;
public $model;
public function __construct($color, $model)
{
$this->color = $color;
$this->model = $model;
}
public function message()
{
return "My car is a " . $this->color . " " . $this->model . "!";
}
}
Output:
$myCar = new Car("red", "Volvo");
object(Car)#1 (2) { ["color"]=> string(3) "red"
var_dump($myCar); ["model"]=> string(5) "Volvo" }
PHP NULL Value

• Null is a special data type which can have only one value: NULL.
• A variable of data type NULL is a variable that has no value assigned to it.
• If a variable is created without any value, then the NULL value is automatically assigned to it.
• Variables can also be emptied by setting the value to NULL:
• Example:
<?php
$x = "Hello world!";
$x = null;
$y;
var_dump($x);
echo "<br>";
var_dump($y);
?>
Output:
NULL
NULL
PHP Resource

• In PHP, Resource is a special data type that refers to any external resource.
• A resource variable acts as a reference to external source of data such as stream file,
database etc.
• PHP uses relevant functions to create these resources.
• For example, fopen() function opens a disk file and its reference is stored in a resource
variable

Example:
<?php
$fp=fopen("Test.txt","w");
var_dump($fp);
?>

Output:
resource(3) of type (stream)
PHP print_r() Function
• The print_r() function prints the information about a variable in a more human-readable way.
• Syntax: print_r($variable,$isStore)
• $ variable: Required parameter . Specifies the variable to be printed
• $isStore: Optional parameter. Its default value is false
• If this parameter is set to true, then the print_r function will store the output in a variable rather than
printing it.
• Example
<?php
$a = "hello world"; //string variable
$b = array("red", "green", "blue"); //array variable
$c = array("raj"=>"35", "yash"=>"37", "amit"=>"43");//array variable
print_r($a);
echo "<br>";
print_r($b);
echo "<br>";
print_r($c);
echo "<br>"; Output:
hello world
$d=print_r($a,true); // $isStore set to true Array ( [0] => red [1] => green [2] => blue )
print_r($d); Array ( [raj] => 35 [yash] => 37 [amit] => 43 )
?> hello world
PHP var_dump() Function
• The var_dump() function returns the data type and the value of variable
• Syntax: var_dump(var1, var2, ...);

• Example:
<?php
$a = 32;
$b = 32.5;
$c = "Hello world!"; Output:
$d = array("red", "green", "blue"); int(32)
float(32.5)
string(12) "Hello world!"
var_dump($a); array(3) { [0]=> string(3) "red" [1]=> string(5) "green"
echo "<br>"; [2]=> string(4) "blue" }
var_dump($b); int(32) float(32
echo "<br>";
var_dump($c);
echo"<br>";
var_dump($d);
echo"<br>";
var_dump($a, $b);// Dump two variables
?>
Type Juggling
• PHP is known as a dynamically typed language.
• In PHP data type of variable changes dynamically according to the value assigned to it. This feature is called "type juggling“.
• .
• Example:
<?php
$x = "Hello";//data type of $x is string
var_dump($x);
echo "<br>";

$x = 10; //data type of $x is integer


var_dump($x);
echo "<br>";

$x= 10.50; //data type of $x is float


var_dump($x);
echo "<br>";

?>
Output:
string(5) "Hello"
int(10)
float(10.5)
Type Casting
• Typecasting is a process of converting a variable from one data type to another data type
• Typecasting is the explicit conversion of data type.
• A type can be cast by inserting one of the casts in front of the variable
• Casting in PHP is done with these statements:
•(string) - Converts to data type String
•(int) - Converts to data type Integer
•(float) - Converts to data type Float
•(bool) - Converts to data type Boolean
•(array) - Converts to data type Array
•(object) - Converts to data type Object
•(unset) - Converts to data type NULL
Type Casting
Example:
<pre>
<?php Output:
$a = 5; // Integer float(5)
$b = 5.34; // Float int(5)
$c = "hello"; // String string(5) "hello“
$d = true; // Boolean string(1) "1"
$e = NULL; // NULL string(0) ""
Note that when casting a Boolean into string it
$a = (float) $a; gets the value "1", and when casting NULL into
$b = (int) $b; string it is converted into an empty string "".
$c = (string)$c;
$d = (string)$d;
$e = (string)$e;

//To verify the type of any object in PHP, use the var_dump() function
var_dump($a);
var_dump($b);
var_dump($c);
var_dump($d);
var_dump($e);
Constants
• Constants in PHP are identifiers that are used to store fixed values and
• A constant value cannot change during the execution of the PHP script.
• Rules for constants:
• By default, a PHP constants are 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 underscore.
• There is no need to write a dollar sign ($) before a constant, however one can use a dollar sign before a constant.
• Creating a Constant using define() function:

• Syntax: define( 'CONSTANT_NAME', value, case_insensitive)


• The parameters are as follows:
• name: The name of the constant.
• value: The value of the constant.
• case_insensitive: Its default value is false, Defines whether a constant is case insensitive or case sensitive.
• If this parameter is true then constant is case insensitive and
• If this parameter is false then constant is case sensitive and

• You can also create a case-sensitive constant by using the const keyword
• For example: const MYCAR = "Volvo";

• const vs. define()


• Using const keyword a constant cannot be created inside another block scope, like inside a function or inside
an if statement.
• Using define function a constant can be created inside another block scope.
Constants

Example:
<?php
define("WELCOME", "GeeksforGeeks");//creates a case-sensitive constant
echo WELCOME . "<br>";

define("HELLO", "GeeksforGeeks", true);//creates a case-insensitive constant


echo hello ."<br>";

const MYCAR = "Volvo"; //creates case sensitive constant


echo MYCAR;
?>
Output:
GeeksforGeeks
GeeksforGeeks
Volvo
Expressions and Operators in PHP
• An operators are the symbols that are used to performs a certain operations on values or
operands.
• The expressions are the combination of operands with an operators
• Types of operators in PHP:
1. Arithmetic Operators(+ , - , * , / , % , **)
2. Assignment Operators(= , += , -= , *=, /= , %=)
3. Comparison Operators(== , != , < > , === ,!== , < , <= , > , >=, <=> )
4. Increment/Decrement Operators ( ++ , --)
5. Logical Operators (and , or , xor , && , || , ! )
6. String Operators (. , .=)
7. Array Operators (+ , ==, != , < > , === , !==)
8. Conditional Assignment Operators (?: , ??)
9. Bitwise Operators (& , | , ^ , ~ , << , >>)
PHP Arithmetic Operators
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 Returns $x raised to the $yth power

• The PHP arithmetic operators are used to perform common arithmetical operations, such as
addition, subtraction, multiplication etc.
PHP Arithmetic Operators

Example:
<?php
echo "Arithmetic Operators:";
$x = 5;
$y = 2;
echo("<br> Addition is:".($x + $y));
echo("<br> subtraction is:".($x- $y));
echo("<br> Multiplication is:".($x* $y));
echo("<br> Division is:".($x / $y));
echo("<br> Modulus is:".($x % $y));
echo("<br> Exponentiation is:".($x ** $y));
?>

Output:
Arithmetic Operators:
Addition is:7
subtraction is:3
Multiplication is:10
Division is:2.5
Modulus is:1
PHP Assignment operators
Operator Name Example Same as... Result
Assigns value of right operand to the
= Assign $x = $y $x = $y
left operand

+= Add then Assign $x += $y $x=$x + $y Sum of $x and $y

-= Subtract then Assign $x -= $y $x=$x - $y Difference of $x and $y

*= Multiply then Assign $x *= $y $x=$x * $y Product of $x and $y

Divide then Assign


/= $x /= $y $x=$x / $y Quotient of $x and $y
(quotient)

Divide then Assign


%= $x %= $y $x=$x % $y Remainder of $x divided by $y
(remainder)

Exponentiation and $x=$x **$y Returns $x raised to the $yth power


**= $x **= $y
Assign

• The PHP assignment operators are used to assign value to a variable


PHP Assignment
Example:
<?php
operators
Output:
echo "Assignment Operators";
Assignment Operators
$x =20; //simple assign operator
x=20
echo("<br> x=". $x);
x=x+10: 30
x=x-10: 20
$x+=10; //add then assign operator
x=x*10: 200
echo("<br> x=x+10: ".$x); x=x/10: 20
x=x%10: 0
$x-=10; //substract then assign operator x=x**10: 0
echo("<br> x=x-10: ".$x);

$x*=10; //multiply then assign operator


echo("<br> x=x*10: ".$x);

$x/= 10; //divide then assign(quotient) operator


echo("<br> x=x/10: ".$x);

$x%=10; //divide then assign(remainder) operator


echo("<br> x=x%10: ".$x);
PHP Comparison Operators
Operator Name Example Result
== Equal $x = = $y Returns true if $x is equal to $y
!= 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
=== Identical $x = = = $y Returns true if $x is equal to $y, and they are of the
same types
!== Not identical $x !== $y Returns true if $x is not equal to $y, and they are of the
different types
< Less than $x < $y Returns true if $x is less than $y
<= Less than or equal to $x <= $y Returns true if $x is less than or equal to $y
> Greater than $x > $y Returns true if $x is greater than $y
>= Greater than or equal to $x >= $y Returns true if $x is greater than or equal to $y
<=> Spaceship $x <=> $y This operator is used to compare two values or
operands but instead of returning Boolean value it
returns integer values
Returns 0 if both the operands are equal
Returns 1 if the left operand is greater
Returns -1 if the right operand is greater
Introduced in PHP 7

• The PHP comparison operators are used to compare two values (number or string) or operands
PHP Comparison Operators
Example:
<?php
echo "Comparison Operators";
$x=10; Output:
$y=20;
echo "<br>"; Comparison Operators
var_dump($x==$y);//equal to operator
bool(false)
echo "<br>"; bool(true)
var_dump($x!=$y);//not equal to operator (<>) bool(false)
bool(true)
echo "<br>";
var_dump($x===$y);//identical operator
bool(true)
bool(true)
echo "<br>"; bool(false)
var_dump($x!==$y);//not identical operator bool(false)
echo "<br>";
var_dump($x<$y);//less than operator

echo "<br>";
var_dump($x<=$y);//less than or equal to operator

echo "<br>";
var_dump($x>$y);//greater than operator

echo "<br>";
var_dump($x>=$y);//greater than or equal to operator
?>
PHP Comparison Operators
Example:
<?php
echo "Spaceship Operators";
$x = 10;
$y = 10;
echo("<br>".($x <=> $y)); // returns 0 because $x and $y values are equal

$x = 15;
$y = 10;
echo("<br>".($x <=> $y)); // returns 1 because $x is greater than $y

$x = 5;
$y = 10;
echo("<br>".($x <=> $y)); // returns -1 because $x is less than $y

?>

Output:
Spaceship Operators
0
1
-1
PHP Increment / Decrement Operators

Operator Name Example Result

++ Pre-increment ++$x First increments $x by one, then returns $x

++ Post-increment $x++ First returns $x, then increments $x by one

-- Pre-decrement --$x First decrements $x by one, then returns $x

-- Post-decrement $x-- First returns $x, then decrements $x by one

• Increment / Decrement Operators are called the Unary operators as they works on single
operand
PHP Increment / Decrement Operators

Example:

<?php
echo "Increment / Decrement Operators"; Output:
$x=3; Increment / Decrement Operators
echo ("<br> first increments then prints:".++$x); first increments then prints:4
first prints then increments:3
$x=3; first decrements then prints:2
echo ("<br> first prints then increments:".$x++); first prints then decrements:3

$x=3;
echo ("<br> first decrements then prints:".--$x);

$x=3;
echo ("<br> first prints then decrements:".$x--);

?>
PHP Logical Operators
Operator Name Example Result
And And $x and $y True if both $x and $y are true
Or Or $x or $y True if either $x or $y is true
Xor Xor $x xor $y True if either $x or $y is true, but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true

• The PHP logical operators are used to combine multiple conditions into single
condition
PHP Logical Operators
Example:
<?php Output:
echo "Logical Operators"; Logical Operators
$x=10; True
$y=20; True
if ($x==10 and $y==20) //logical AND(&&) False
echo ("<br> True"); False
else
echo (" <br> False");

if ($x==10 or $y==20) //logical OR(||)


echo ("<br> True");
else
echo (" <br> False");

if ($x==10 xor $y==20) //logical XOR


echo ("<br> True");
else
echo (" <br> False");

if (!($x==10 && $y==20)) //logical NOT


echo ("<br> True");
else
echo (" <br> False");
?>
PHP String Operators
Operator Name Example Result
. Concatenation $x . $y Concatenation of $x and $y
.= Concatenation $x .= $y First concatenates then assigns, same as
assignment $x = $x . $y
• PHP has two operators that are specially designed for strings.

Example:
<?php
echo "String Operators"; Output:
$x="Hello"; String Operators
$y="World!"; HelloWorld!
HelloWorld!
$z=$x.$y;
echo ("<br>".$z);

$x.=$y;
echo ("<br>".$x);
?>
PHP Array Operators
Operator Name Example Result

+ Union $x + $y Union of $x and $y


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

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

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

Returns true if $x and $y have the same key/value pairs


=== Identity $x === $y in the same order and of the same types

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

• The PHP array operators are used to compare two arrays.


PHP Array Operators
Example: Output:
<?php Array operators
echo "Array operators <br>"; Array ( [a] => red [b] => green [c] => blue [d] => yellow )
$x = array("a" => "red", "b" => "green"); bool(false)
$y = array("c" => "blue", "d" => "yellow"); bool(true)
bool(true)
print_r($x + $y); // union operator bool(false)
bool(true)
echo "<br>";
var_dump($x == $y);//equality operator

echo "<br>";
var_dump($x != $y); //inequality operator

echo "<br>";
var_dump($x <> $y);//inequality operator

echo "<br>";
var_dump($x === $y);//identity operator

echo "<br>";
var_dump($x !== $y);//non-identity operator
?>
PHP Conditional Assignment Operators
Operator Name Example Result
Returns the value of $x.
?: Ternary $x = expr1 ? expr2 : expr3 The value of $x is expr2 if expr1 = TRUE.
The value of $x is expr3 if expr1 = FALSE
Returns the value of $x.
The value of $x is expr1 if expr1 exists, and
Null is not NULL.
?? $x = expr1 ?? expr2
coalescing If expr1 does not exist, or is NULL, the value
of $x is expr2.
Introduced in PHP 7

• The PHP conditional assignment operators are used to assign a value to variable depending on
conditions
Ternary operator
• The ternary operator (?:) is a conditional operator used to evaluate the condition, if condition is
true then statement 1 is executed and if condition is false then statement 2 is executed.
• It is called a ternary operator because it takes three operands- a condition, a result statement for
true, and a result statement for false.
• The use of the ternary operator will make the code shorter as compared with IF ELSE statement.

• Syntax:
Variable = (Condition) ? (Statement1) : (Statement2);

• Example:
<?php
$age = 10;
$x= ($age >= 18) ? "Adult" : "Not Adult";
echo $x;
?>
• Output:
Not Adult
Null Coalescing Operator

• The Null Coalescing Operator is represented by the "??" symbol.


• It is Introduced in PHP 7
• It returns its first operand if it exists and is not null; otherwise, it returns its second operand.

• Syntax:
$Var = $operand1 ?? $operand2;

• Example:
<?php
$x=null;
$y="green";
$color = $x ?? $y;
echo "The color is: ".$color;
?>

Output:
The color is: green
PHP Bitwise Operators
Operator Name Example Description
It returns 1 , only if both the bits are 1; otherwise it
& Bitwise AND $x & $y returns 0

It returns 1, if one of the bits is 1; otherwise it


| Bitwise OR $x | $y
returns 0
It returns 1 ,if any one of the bit is 1 (but not both
^ Bitwise XOR $x ^ $y
bits are 1); otherwise, it returns 0.

~ Bitwise NOT ~ $x It returns one’s complement of a bits

Bitwise Left It shifts the bits of left operand towards the left by
<< $x << $y
Shift the number of bits given in the right operand.
Bitwise Right It shifts the bits of left operand towards the right by
>> $x >>$y
Shift the number of bits given in right operand.

• Bitwise Operator operates on binary digits that are used to perform bit level operations
on the operands
PHP Bitwise Operators
Example:
<?php
echo "Bitwise Operators"; Bitwise Operators
$x=5; Bitwise AND: 1
$y=1; Bitwise OR: 5
Bitwise XOR: 4
echo("<br>Bitwise AND: ". ($x & $y)); Bitwise NOT: -6
Bitwise Left Shift: 10
echo("<br>Bitwise OR: ".($x|$y)); Bitwise Right Shift: 2
echo("<br>Bitwise XOR: ".($x^$y));

echo("<br>Bitwise NOT: ".(~$x));

echo("<br>Bitwise Left Shift: ".($x << $y));

echo("<br>Bitwise Right Shift: " .($x >> $y));


?>
Decision Making Control Statements

• Conditional statements are used to perform different actions based on different


conditions.

• If Statement
• If-else Statement
• If-elseif-else Statement
• Nested if Statement
• Switch Statement
• Break Statement
• Continue Statement
If Statement
• If statement is used to executes the block of code only if the specified condition evaluates to true.
• Syntax
if(condition)
{
//code to be executed if condition is true
}
• Example:
<?php
$a=10;
if($a==10)
{
echo (“ The number is:".$a);
}
?>
Output:
number is:10
If-else Statement
• The if...else statement executes some code if a condition is true and another code if that condition
is false.
• Syntax
if (condition)
{ // code to be executed if condition is true;
}
else
{ // code to be executed if condition is false;
}
• Example:
<?php
$a=10;
if($a>0)
{ echo ("number is positive");
}
else
{ echo ("number is negative");
}
?>
If-else Statement

• PHP Program to display given number is even or odd


<?php
$num=12;
if($num%2==0){
echo "$num is even number";
}
else{
echo "$num is odd number";
}
?>

• Output:
12 is even number
If-elseif-else Statement
• The if...elseif...else statement executes different codes for more than two conditions.
• Syntax
if (condition1)
{ //code to be executed if condition1 is true;
}
elseif (condition2)
{ // code to be executed if condition1 is false and condition2 is true;
}
else
{ // code to be executed if all conditions are false;
}
If-elseif-else Statement
• Example:
<?php
$per=75;
if($per>=75)
{ echo "Distinction";
}
elseif($per>=60 and $per<75)
{ echo "First Class";
}
elseif($per>=50 and $per<60)
{ echo "Second Class";
}
elseif($per>=40 and $per<50)
{ echo "Pass Class";
}
else
{echo "Fail";
}
?>
Nested If statement
• The if statements inside another if statement is called nested if statements. or
• The nested if statement consists the if block inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.
• Syntax
if (condition1)
{ //code to be executed if condition1 is true
if (condition2)
{
//code to be executed if both condition1 and condition2 are true
}
}
Nested If statement
• Example:
<?php
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
• Output:
• Above 10 but not above 20
Switch statement
• The switch statement is used to perform different actions based on different conditions. or
The switch statement is used to select one of many blocks of code to be executed.
• This is how it works:
• The expression is evaluated once.
• The value of the expression is then compared with the values of each case.
• If there is a match, the block of code associated with that case is executed.
• The default code block is executed if there is no match.
• The break keyword breaks out of the switch block.

• Syntax
switch (expression) {
case value1:
// Code to be executed if expression matches value1
break;
case value2:
// Code to be executed if expression matches value2
break;
// additional cases as needed
default:
// Code to be executed if none of the cases match the expression
break;
Switch statement
Example:
<?php
$a=10;
$b=20;
$ch=3;
switch ($ch) {
case 1:
echo "Addition=".($a+$b);
break;
case 2:
echo "Substraction=".($a-$b);
break;
case 3:
echo "Multiplication=".($a*$b);
break;
case 4:
echo "Division=".($a/$b);
break;
case 5:
echo "Modulus=".($a%$b);
break;
case 6:
echo "Exponentiation=".($a**$b);
break;
default:
echo "Wrong Choice";
break;
}
?>
Output : Multiplication=200
Switch statement
Example:
<?php
$per = 75;
switch (true) {
case ($per >=75):
echo "Distinction";
break;
case ($per >=60 and $per < 75):
echo "First Class";
break;
case ($per >=50 and $per < 60):
echo "Second Class";
break;
case ($per >=40 and $per < 50):
echo "Pass Class";
break;
default:
echo "Fail";
break;
}
?>
Output : Distinction
Switch statement
Example:
<?php
$var = date("D");
echo $var;
switch ($var) {
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;
default:
echo "It is the weekend!";
break;
}
?>
Output :
Break statement
• The break statement is used to jump out of different kind of loops. Or its used to exit from loops
• When break statement is executed inside loop then it terminate the execution of current loop and transfer the control
to the next statement outside the loop.
• A break is usually associated with the if statement
• Syntax:
if (condition)
{
//code to be executed if condition is true
break;
} Output:
• Example: Jump out of the loop when $i is 4 0
1
<?php 2
echo "Output:<br>"; 3
for ($i = 0; $i< 10; $i++)
{
if ($i ==4)
{ break; //Terminate the loop if condition is true.
}
echo "$i <br>";
}
Continue Statement
• The continue statement used to skip the execution of the current iteration in the loop and
continue with the next iteration
• Syntax:
if (condition)
{ //code to be executed if condition is true
continue;
}
Output:
• Example: Move to next iteration if $i = 4
0
1
<?php
2
echo "Output:<br>"; 3
for ($i = 0; $i< 10; $i++) 5
6
{
7
if ($i == 4) 8
{ continue; 9
}
echo $i. "<br>";
}
?>
Loop Control Statements

• Loops are used to execute the same block of code again and again, as long as
a certain condition is true.

• While Loop
• do-while loop
• For Loop
• foreach loop
While Loop
• The while loop executes a block of code as long as the specified condition is true.
• Syntax:
while(condition){
//code to be executed
}
While Loop
• Example: PHP program to display numbers from 1to 10 using while Loop
<?php
$n=1;
while($n<=10){
echo "$n <br>";
$n++;
}
?>
• Output:
1
2
3
4
5
6
7
8
9
10
Do-While Loop
• The do...while loop will execute the block of code at least once, then it will
check the condition, and repeatedly executes the block of code as long as the
specified condition is true.
• do...while loop will execute the block of code at least once, even if the condition
is false
• Syntax
do{
//code to be executed
}while(condition);
Do-While Loop
• Example: PHP program to display numbers from 1to 10 using do-while loop
<?php
$n=1;
do{
echo "$n <br>";
$n++;
}while($n<=10)
?>
Output:
1
2
3
4
5
6
7
8
9
10
For Loop
• PHP for loop can be used to traverse set of code for the specified number of times.
• The for loop is used to execute a block of code repeatedly, specified number of times.
• for loop is used when you already know how many times you want to execute a block of code.
• Syntax
for(initialization; condition; increment/decrement){
//code to be executed
}
For Loop
• Example: PHP program to display numbers from 1-10 in a sequence using for loop.

<?php
for ($n = 1; $n <= 10; $n++){
echo "The number is: $n<br>";
}
?>

Output:
1
2
3
4
5
6
7
8
9
10
For Loop
Example: PHP program to display even numbers from 1-50 (using for ,while and do..while loop.
<?php
echo "Even numbers from 1-50 using for loop<br>"; Output:
Even numbers from 1-50 using for loop
for ($i = 1; $i <=50; $i++) { 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
if ($i % 2 == 0) 40 42 44 46 48 50
echo " ".$i;
} Even numbers from 1-50 using while loop
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
40 42 44 46 48 50
echo "<br><br>Even numbers from 1-50 using while loop<br>";
$i = 1; Even numbers from 1-50 using do-while loop
while ($i <= 50) { 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38
40 42 44 46 48 50
if ($i % 2 == 0)
echo " ".$i;
$i++;
}

echo "<br><br>Even numbers from 1-50 using do-while loop<br>";


$i = 1;
do {
if ($i % 2 == 0)
echo " ".$i;
$i++;
} while ($i <= 50);
?>
For Loop
Example: PHP program to display factorial of number (using for ,while and do..while loop).
<?php
echo "factorial of number using for loop<br>";
$num=5;
$fact=1; Output:
for($i=1;$i<=$num;$i++){ factorial of number using for loop
$fact=$fact*$i; factorial of 5 is: 120
}
echo "factorial of $num is: ".$fact;
echo "<br><br>factorial of number using while loop<br>"; factorial of number using while loop
$num=5; factorial of 5 is: 120
$fact=1;
$i=1; factorial of number using do while loop
while ($i <=$num) { factorial of 5 is: 120
$fact=$fact*$i;
$i++;
}
echo "factorial of $num is: ".$fact;
echo "<br><br>factorial of number using do while loop<br>";
$num=5;
$fact=1;
$i=1;
do {
$fact=$fact*$i;
$i++;
} while ($i <=$num);
echo "factorial of $num is: ".$fact;
Foreach Loop
• The foreach loop is used to loop through(iterate or traverse) the elements of an array.
• On each loop iteration, the value of the current array element is assigned to $value variable and
the internal array pointer is incremented by one, until it reaches the last element of an array
• (i.e In first iteration value of 1 st element in an array is assigned to $value variable ,the internal
array pointer is incremented by one then in second iteration value of 2 st element in an array is
assigned to $value variable and so on)
• The foreach loop works with arrays and objects, if you try to use it with the variables of different
data type then it will issue an error.

• Syntax1:
foreach ($array_var as $value)
{ //code to be executed
}
• Syntax2:
foreach ($array_var as $key=>$value)
{ //code to be executed
}
Foreach Loop
Example: PHP program to print elements of array using foreach loop or
Loop through the items of an indexed array

<?php
//declare an indexed array
$student=array("raj","ram","sagar");

//access elements of array using foreach loop


foreach ($student as $value){
echo "$value<br>";
}
?>
Note: For every loop iteration, the value of the current array element is assigned to the variable $x.
the array pointer is incremented by one, until it reaches the last array element.
Output:
raj
ram
sagar
Foreach Loop

Example: PHP program to print both the key and the value pairs from an associative array or
Loop through the items of an associative array

<?php
//declare an associative array
$student= array("name"=>"raj","age"=>25 , "email"=>"raj123@gmail.com");
//access elements of array using foreach loop
foreach ($student as $key => $value) {
echo "$key : $value <br>";
}
?>

Output:
name : raj
age : 25
email : raj123@gmail.com

You might also like