0% found this document useful (0 votes)
30 views49 pages

PHP Module 3 Part2

The document provides an overview of variable type casting and operators in PHP, detailing how to convert data types and perform various operations such as arithmetic, comparison, and logical operations. It explains different types of loops (for, foreach, while, do-while) and conditional statements (if, switch) used for control flow in PHP programming. Additionally, it covers the use of break and continue statements to manage loop execution.

Uploaded by

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

PHP Module 3 Part2

The document provides an overview of variable type casting and operators in PHP, detailing how to convert data types and perform various operations such as arithmetic, comparison, and logical operations. It explains different types of loops (for, foreach, while, do-while) and conditional statements (if, switch) used for control flow in PHP programming. Additionally, it covers the use of break and continue statements to manage loop execution.

Uploaded by

mahisd8113
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Variable Type Casting

• Type casting is converting a variable or value into a desired data type.


• This is very useful when performing arithmetic computations that
require variables to be of the same data type.
• Type casting in PHP is done by the interpreter.
• Type casting produces a copy leaving the original variable untouched.
• $newvar = (integer) $originalvar;
• $test = 1.5;
$new = (int)$test;
echo $new; // output 1
Cast Operators Conversion
(array) Array
(bool) or (boolean) Boolean
(int) or (integer) Integer
(object) Object
(real), (double), or Float
(float)
(string) String
PHP Operators
• Operators are used to perform operations on variables and
values. PHP divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Increment/Decrement operators
• Logical operators
• String operators
• Array operators
• Conditional assignment operators
ARITHMETIC OPERATORS
Operator Name Example Explanati
on
+ Addition $a + $b Sum of
operands
- Subtracti $a - $b Differenc
on e

of
operands
* Multiplica $a * $b Product
t of
ion operand
s
/ Division $a / $b Quotient
of
operand
s
% Modulus $a % $b Remaind
er of
operands
COMBINED ASSIGNMENT
OPERATORS
Operator Example Equivalent Operation

+= $x += $y $x = $x + $y Addition

-= $x -= $y $x = $x – $y Subtraction

*= $x *= $y $x = $x * $y Multiplication

/= $x /= $y $x = $x / $y Division

%= $x %= $y $x = $x % $y Modulus
**= $z **= $y $x = $x ** $y Exponentiatio
n
OPERATORS
•ASSIGNMENT OPERATOR
$x = 1;
CONCATENATION OPERATOR or STRING OPERATOR
PHP uses the concatenation operator (.) to concatenate
two strings.
ECHO “HI” . “FRIENDS” ; //HI FRIENDS
Use concatenation assignment operator (.=) to
concatenate strings and assign the result to a variable in
a single statement.
PHP COMPARISON OPERATOR($x=4)
OPERATOR NAME EXAMPLE RESULT
== Equivalence $x==5 FALSE
!=,<> not equivalence $x!=5 TRUE
=== IDENTICAL $x===4 true
!== not identical $x!==“4” true
> Greater than $x > 4 false
>= greater than equal to $x >=4 true
< less than $x<4 false
<= less than equal to $x<=4 true
<=> spaceship operator $x<=>$y
Auto increment and auto decrement
operator
Opertor name example result
$x++ Post increment operator $x++ $x+1
$x-- post decrement $x-- $x-1
operator
++$x pre increment operator ++$x $x+1
--$x pre decrement operator --$x $x-1
LOGICAL OPERATORS
OPERATOR NAME EXAMPLE RESULT
|| OR true||false true
or OR true or false true
xor XOR true xor true false
&& AND true && false false
and AND true and false false
! NOT !true false
ARRAY OPERATOR
OPERATOR NAME EXAMPLE
+ UNION $X+$Y
== EQUALITY $X==$Y
=== IDENTICAL $X===$Y
!=,<> INEQUALITY $X!=$Y
!== NOT IDENTICAL $X!==$Y
PHP Conditional Assignment
Operators

OPERATOR NAME EXAMPLE


?: TERNARY $x= expr1 ? Expr2 : expr3
?? Null coalescing $x = expr1 ?? Expr2

Arithmetic operator
** Exponentiation $x**$y
Operator Precedence
• The following table lists the operators in order of precedence, with the highest-precedence ones at the top.
Operators on the same line have equal precedence, in which case associativity decides grouping.
Operator Precedence
Operators Purpose

clone new clone and new


** Exponentiation

++ -- increment/decrement

~(int) (float) (string) (array) Casting


(object) (bool)

instanceof Types

! Logical

*/ multiplication/division

% Modulo

+-. arithmetic and string

<< >> bitwise shift

< <= > >= Comparison


Operator Precedence
== != === !== <> <=> Comparison

& bitwise and/references

^ bitwise XOR

| bitwise OR

&& logical and

|| logical or

?? null coalescing

?: Ternary

= += -= *= **= /= .= %= &= |= ^= <<= >>= ??= assignment operators

yield from yield from

yield yield

print print

and logical

xor logical

or logical
PHP Conditional Statements
•Conditional statements are used to perform different actions
based on different conditions.
In PHP we have the following conditional statements:
•If statement - executes some code if one condition is true
•If…else statement - executes some code if a condition is true
and another code if that condition is false
•If…elseif…else statement - executes different codes for more than
two conditions
•Switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
•The if statement executes some code if one condition is true.
•Syntax
if (condition) {
code to be executed if condition is true;
}

Example
if ($t < "20") {
echo "Have a good day!";
}
PHP - The 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 if ($t < "20") {
echo "Have a good
day!";
} else {
echo "Have a good night!";
}
PHP - The if...elseif...else Statement
• The if...elseif...else statement executes different codes for more than two conditions.
• Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
PHP - The switch Statement
• The switch statement is used to perform different actions based on different conditions.
• Use switch statement to select one of many blocks of code to be executed.

• SYNTAX
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
PHP - The switch Statement
EXAMPLE
switch ($favcolor)
{ case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
PHP For Loop
• PHP for loop can be used to traverse set of code for the specified number
of times.
• It should be used if the number of iterations is known otherwise use while
loop. This means 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
}
PHP For Loop
•initialization - Initialize the loop counter value. The initial value of the
for loop is done only once. This parameter is optional.
•condition - Evaluate each iteration value. The loop continuously
executes until the condition is false. If TRUE, the loop execution
continues, otherwise the execution of the loop ends.
•Increment/decrement - It increments or decrements the value of the
variable.
•All three parameters are optional, but semicolon (;) is must to pass in
for loop. If we don't pass parameters, it will execute infinite times.
For example
Example
<?php
for($n=1;$n<=5;$n++){
echo "$n<br/>";
}
?>
OUTPUT
1
2
3
4
5
PHP foreach loop
•The foreach loop is used to traverse the array elements. It works only
on array and object. It will issue an error if you try to use it with the
variables of different datatype.
•The foreach loop works on elements basis rather than index. It
provides an easiest way to iterate the elements of an array.
•In foreach loop, we don't need to increment the value.
•SYNTAX 1
foreach ($array as $value) {
//code to be executed
}
PHP foreach loop
SYNTAX 2
foreach ($array as $key => $element) {
//code to be executed
}
Foreach example
<?php
$season=array("summer","winter","spring","autumn");
foreach( $season as $arr )
{ echo "Season is: $arr<br />";
}
?>
OUTPUT
Season is summer
Season is winter
Season is spring
Season is autumn
Foreach example
<?php
//declare array
$employee = array (
"Name" => "Alex",
"Email" => "alex_jtp@[Link]",
"Age" => 21,
"Gender" => "Male"
);

//display associative array element through foreach loop


foreach ($employee as $key => $element)
{ echo $key . " : " . $element;
echo "</br>";
}
?>
Output
Name : Alex
Email : alex_jtp@[Link]
Age : 21
Gender : Male
Foreach example
<?php
//declare multi-dimensional array
$a = array();
$a[0][0] = "Alex";
$a[0][1] = "Bob";
$a[1][0] = "Camila";
$a[1][1] = "Denial";
//display multi-dimensional array elements through foreach loop
foreach ($a as $e1) {
foreach ($e1 as $e2) {
echo "$e2\n";
}
}
?>
Output
Alex Bob Camila Denial
PHP While Loop
•PHP while loop can be used to traverse set of code like for loop. The
while loop executes a block of code repeatedly until the condition is
FALSE. Once the condition gets FALSE, it exits from the body of loop.
•It should be used if the number of iterations is not known.
•The while loop is also called an Entry control loop because the
condition is checked before entering the loop body. This means that
first the condition is checked. If the condition is true, the block of
code will be executed.
While loop
Syntax
while(condition){
//code to be executed
}
PHP While Loop Example
<?php
$n=1;
while($n<=5){
echo "$n<br/>";
$n++;
}
?>
Output:
1
2
3
4
5
PHP do-while loop
• PHP do-while loop can be used to traverse set of code like PHP while loop.
The PHP do-while loop is guaranteed to run at least once.
• The PHP do-while loop is used to execute a set of code of the program
several times. If you have to execute the loop at least once and the
number of iterations is not even fixed, it is recommended to use the do-
while loop.
• It executes the code at least one time always because the condition is
checked after executing the code.
• The do-while loop is very much similar to the while loop except the
condition check. The main difference between both loops is that while loop
checks the condition at the beginning, whereas do-while loop checks the
condition at the end of the loop.
Do while loop
Syntax
do{
//code to be executed
}while(condition);
Example
<?php
$n=1;
do{
echo "$n<br/>";
$n++;
}while($n<=5);
?>
Output
1
2
3
4
5
Difference between while and do-
while loop
while Loop do-while loop
The while loop is The do-while loop
also is also named as
exit control loop.
named as entry
control loop.
The body of the The body of the
loop does not loop executes at
execute if the least once, even
condition is false. if the condition is
false.
Condition checks Block of
first, and then statements
block of executes first
and then
statements
executes. condition checks.
This loop does Do-while loop use
not use a semicolon
semicolon to
terminate the to terminate the
loop. loop.
PHP Break
•PHP break statement breaks the execution of the current for, while,
do-while, switch, and for-each loop. If you use break inside inner
loop, it breaks the execution of inner loop only.
•The break keyword immediately ends the execution of the loop or
switch structure. It breaks the current flow of the program at the
specified condition and program control resumes at the next
statements outside the loop.
Syntax
jump statement;
break;
PHP Break example
<?php
for($i=1;$i<=10;$i++){
echo "$i <br/>";
if($i==5){
break;
}
}
?>
Output
1
2
3
4
5
PHP continue statement
• The PHP continue statement is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified
condition.
• The continue statement is used within looping and switch control structure
when you immediately jump to the next iteration.
• The continue statement can be used with all types of loops such as - for,
while, do-while, and foreach loop. The continue statement allows the user
to skip the execution of the code for the specified condition.
Syntax
jump-statement;
continue;
PHP Continue Example
<?php
//outer loop
for ($i =1; $i<=3; $i++) {
//inner loop
for ($j=1; $j<=3; $j++) {
if (!($i == $j) ) {
continue; //skip when i and j does not have same values
}
echo $i.$j;
echo "</br>";
}
}
?>
Output
11
22
33

You might also like