0% found this document useful (0 votes)
5 views90 pages

Module 2 - Merged

The document provides an overview of PHP operators and control structures, detailing various types of operators such as arithmetic, comparison, logical, assignment, and conditional operators. It explains operator precedence and associativity, as well as control structures like conditional statements (if, switch) and looping statements (while, for, do-while). Additionally, it covers the use of escape sequences and the rules for break, continue, and goto statements.

Uploaded by

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

Module 2 - Merged

The document provides an overview of PHP operators and control structures, detailing various types of operators such as arithmetic, comparison, logical, assignment, and conditional operators. It explains operator precedence and associativity, as well as control structures like conditional statements (if, switch) and looping statements (while, for, do-while). Additionally, it covers the use of escape sequences and the rules for break, continue, and goto statements.

Uploaded by

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

Applications Development and

Emerging Technologies
MODULE 2
PHP Operators and Control
Structures
PHP Operators and Control Structures

Objectives
• To understand the different types of operators that are
available on PHP.
• To know what is operator precedence and operator
associativity in PHP.
• To ensure that programs expression are logically correct by
using the correct referencing values of its precedence.
• To use escape sequence properly in the program.
• To know the different approach of control structures.
• To know the fundamentals syntax for conditional and
looping structures.
• To properly use the compound expression using the logical
operators.
• To know the rules of break, continue, and goto statements.
• To see some alternative enclosure for control structures.
PHP Operators and Control Structures

Operators
An operator is a symbol that specifies a particular action in an expression

Operator Precedence, Associativity, and Pupose


PHP Operators and Control Structures

Operator Precedence, Associativity, and Pupose

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.124
PHP Operators and Control Structures

Operator Precedence
is a characteristic of operators that determines the order in which they
evaluate the operands surrounding them.

Output:
PHP Operators and Control Structures

Operator Associativity
is a characteristic of an operator specifies how operations of the same
precedence are evaluated as they are executed.

Output:

Example:
PHP Operators and Control Structures

Arithmetic Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.124

Assignment Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.126
PHP Operators and Control Structures

Increment and Decrement Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.127

Example: Output:
PHP Operators and Control Structures

Comparison Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.129

Example: Output:
PHP Operators and Control Structures

Logical Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.128
Equality Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.129
PHP Operators and Control Structures

Bitwise Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.130

Example: Output:
PHP Operators and Control Structures

Escape Sequences

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.132
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements

if statement
syntax: elseif statement
if(expression) { syntax:
statement… if(expression) {
} statement…
}
else statement elseif(expression) {
syntax: statement…
if(expression) { } else {
statement… statement…
} else { }
statement
}
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Example:
Output:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Nested if…else

Output:
Example:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Compound expression using logical operators

Output:
Example:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


switch statement
syntax:
switch($category){
case opt1:
statement…
break;
case opt2:
statement…
break;
case opt3:
statement…
break;

default:
statement…
}
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Switch Statement

Example: Output:
PHP Operators and Control Structures

PHP Control Structures: Looping Statements

while statement for statement


syntax: syntax:
while(expression){ for(expr1;expr2;expr3)
statement… {
} statement…
}
do … while statement
syntax:
do{
statement…
}while(expression);
PHP Operators and Control Structures

PHP Control Structures: Looping Statements

Example: Output:
PHP Operators and Control Structures

PHP Control Structures: break, continue,


and goto statement

break
break statement is placed within the code of a loop to cause
the program to break out of the loop statement.

continue
continue statement causes execution of the current loop
iteration to end and commence at the beginning of the next iteration.

goto … label:
goto statement is used to jump to other section of the
program to support labels.
PHP Operators and Control Structures

PHP Control Structures: break, continue,


and goto statement

Example:
Output:
PHP Operators and Control Structures

PHP Control Structures: alternative enclosure syntax

Involves replacing the opening bracket with a colon(:) and


replacing the closing bracket with endif;, endwhile;,endfor;,
endswitch

Example: Output:
PHP Operators and Control Structures

Summary
• Simplifying expression needs to follow a general precedence set by
PHP scripts.
• An operator specifies a particular action in a given expression.
• Available PHP operators are arithmetic, conditional, assignment,
logical and bitwise operator.
• Operator precedence characteristics determines the order in which
they evaluate the operands surrounding them.
• Operator associativity characteristic specifies how operations of the
same precedence are evaluated as they are executed.
• Post increment or decrement always execute the statement first
before incrementing or decrementing the value of a given variable.
• Pre increment or decrement always increment or decrement its
variable value before executing the statement.
• Escape sequence has its own special task in executing the string
as an output.
PHP Operators and Control Structures

Summary (Continue)
• Conditional statements are statement the will execute statement
inside a block if a given condition is true
• Use compound expression to minimize the process of coding using
nested if statement.
• break statement caused the program to break if used.
• continue statement end the current loop and continue to next
iteration.
• goto statement used to jump to other section of the program.
• Alternative enclosure syntax is available for if, while, for, foreach,
and switch control.
What is Operator? Simple answer can be given using expression 4 + 5 is equal to 9.
Here 4 and 5 are called operands and + is called operator. PHP language supports
following type of operators.

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
Let’s have a look on all operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by PHP language −
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiply both operands A * B will give


200

/ Divide numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer B % A will give 0


division

++ Increment operator, increases integer value by one A++ will give 11

-- Decrement operator, decreases integer value by one A-- will give 9


Comparison Operators
There are following comparison operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example

== Checks if the value of two operands are equal or not, if yes (A == B) is


then condition becomes true. not true.

!= Checks if the value of two operands are equal or not, if values (A != B) is


are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value of (A > B) is not
right operand, if yes then condition becomes true. true.

< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.

Logical Operators
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then −

Operator Description Example


and Called Logical AND operator. If both the operands are true then (A and B) is
condition becomes true. true.

or Called Logical OR Operator. If any of the two operands are non (A or B) is


zero then condition becomes true. true.

&& Called Logical AND operator. If both the operands are non zero (A && B) is
then condition becomes true. true.

|| Called Logical OR Operator. If any of the two operands are non (A || B) is


zero then condition becomes true. true.

! Called Logical NOT Operator. Use to reverses the logical state !(A && B) is
of its operand. If a condition is true then Logical NOT operator false.
will make false.

Assignment Operators
There are following assignment operators supported by PHP language −

Operator Description Example

= Simple assignment operator, Assigns values from C = A + B will assign


right side operands to left side operand value of A + B into C

+= Add AND assignment operator, It adds right operand C += A is equivalent to


to the left operand and assign the result to left C=C+A
operand

-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to


operand from the left operand and assign the result to C=C-A
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to
operand with the left operand and assign the result to C=C*A
left operand

/= Divide AND assignment operator, It divides left C /= A is equivalent to


operand with the right operand and assign the result C=C/A
to left operand

%= Modulus AND assignment operator, It takes modulus C %= A is equivalent


using two operands and assign the result to left to C = C % A
operand

Conditional Operators
There is one more operator called conditional operator. This first evaluates an
expression for a true or false value and then execute one of the two given statements
depending upon the result of the evaluation. The conditional operator has this syntax −

Operator Description Example

?: Conditional If Condition is true ? Then value X : Otherwise value


Expression Y

Operators Categories
All the operators we have discussed above can be categorized into following
categories −
• Unary prefix operators, which precede a single operand.
• Binary operators, which take two operands and perform a variety of arithmetic
and logical operations.
• The conditional operator (a ternary operator), which takes three operands and
evaluates either the second or third expression, depending on the evaluation of
the first expression.
• Assignment operators, which assign a value to a variable.
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the
addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
will be evaluated first.

Category Operator Associativity

Unary ! ++ -- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %= Right to left


PHP Operators
In this tutorial you will learn how to manipulate or perform the operations on
variables and values using operators in PHP.

What is Operator in PHP


Operators are symbols that tell the PHP processor to perform certain actions. For
example, the addition (+) symbol is an operator that tells PHP to add two
variables or values, while the greater-than (>) symbol is an operator that tells PHP
to compare two values.

The following lists describe the different operators used in PHP.

PHP Arithmetic Operators


The arithmetic operators are used to perform common arithmetical operations,
such as addition, subtraction, multiplication etc. Here's a complete list of PHP's
arithmetic operators:

Operator Description 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
The following example will show you these arithmetic operators in action:

Example
Run this code »
<?php
$x = 10;
$y = 4;
echo($x + $y); // 0utputs: 14
echo($x - $y); // 0utputs: 6
echo($x * $y); // 0utputs: 40
echo($x / $y); // 0utputs: 2.5
echo($x % $y); // 0utputs: 2
?>
PHP Assignment Operators
The assignment operators are used to assign values to variables.

Operator Description Example Is The Same As

= Assign $x = $y $x = $y

+= Add and assign $x += $y $x = $x + $y

-= Subtract and assign $x -= $y $x = $x - $y

*= Multiply and assign $x *= $y $x = $x * $y

/= Divide and assign $x /= $y $x = $x / $y


quotient
%= Divide and assign $x %= $y $x = $x % $y
modulus
The following example will show you these assignment operators in action:

Example

Run this code »


<?php
$x = 10;
echo $x; // Outputs: 10

$x = 20;
$x += 30;
echo $x; // Outputs: 50

$x = 50;
$x -= 20;
echo $x; // Outputs: 30

$x = 5;
$x *= 25;
echo $x; // Outputs: 125

$x = 50;
$x /= 10;
echo $x; // Outputs: 5

$x = 100;
$x %= 15;
echo $x; // Outputs: 10
?>

PHP Comparison Operators


The comparison operators are used to compare two values in a Boolean fashion.

Operator Name Example Result


== Equal $x == $y True if $x is equal to $y
=== Identical $x === $y True if $x is equal to $y, and they are of the same
type
!= Not equal $x != $y True if $x is not equal to $y
<> Not equal $x <> $y True if $x is not equal to $y
!== Not identical $x !== $y True if $x is not equal to $y, or they are not of the
same type
< Less than $x < $y True if $x is less than $y
> Greater than $x > $y True if $x is greater than $y
>= Greater than or equal $x >= $y True if $x is greater than or equal to $y
to
<= Less than or equal to $x <= $y True if $x is less than or equal to $y
The following example will show you these comparison operators in action:

Example

Run this code »


<?php
$x = 25;
$y = 35;
$z = "25";
var_dump($x == $z); // Outputs: boolean true
var_dump($x === $z); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x !== $z); // Outputs: boolean true
var_dump($x < $y); // Outputs: boolean true
var_dump($x > $y); // Outputs: boolean false
var_dump($x <= $y); // Outputs: boolean true
var_dump($x >= $y); // Outputs: boolean false
?>
PHP Incrementing and Decrementing Operators
The increment/decrement operators are used to increment/decrement a
variable's value.

Operator Name Effect


++$x Pre-increment Increments $x by one, then returns $x
$x++ Post-increment Returns $x, then increments $x by one
--$x Pre-decrement Decrements $x by one, then returns $x
$x-- Post-decrement Returns $x, then decrements $x by one
The following example will show you these increment and decrement operators
in action:

Example

Run this code »


<?php
$x = 10;
echo ++$x; // Outputs: 11
echo $x; // Outputs: 11

$x = 10;
echo $x++; // Outputs: 10
echo $x; // Outputs: 11

$x = 10;
echo --$x; // Outputs: 9
echo $x; // Outputs: 9

$x = 10;
echo $x--; // Outputs: 10
echo $x; // Outputs: 9
?>

PHP Logical Operators


The logical operators are typically used to combine conditional statements.

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 following example will show you these logical operators in action:

Example

Run this code »


<?php
$year = 2014;
// Leap years are divisible by 400 or by 4 but not 100
if(($year % 400 == 0) || (($year % 100 != 0) && ($year % 4 ==
0))){
echo "$year is a leap year.";
} else{
echo "$year is not a leap year.";
}
?>

PHP String Operators


There are two operators which are specifically designed for strings.

Operator Description Example Result

. Concatenation $str1 . $str2 Concatenation of $str1 and $str2


.= Concatenation assignment $str1 .= $str2 Appends the $str2 to the $str1

The following example will show you these string operators in action:

Example

Run this code »


<?php
$x = "Hello";
$y = " World!";
echo $x . $y; // Outputs: Hello World!

$x .= $y;
echo $x; // Outputs: Hello World!
?>

PHP Array Operators


The array operators are used to compare arrays:

Operator Name Example Result


+ Union $x + $y Union of $x and $y
== Equality $x == $y True if $x and $y have the same key/value pairs
=== Identity $x === $y True if $x and $y have the same key/value pairs in the same
order and of the same types
!= Inequality $x != $y True if $x is not equal to $y
<> Inequality $x <> $y True if $x is not equal to $y
!== Non- $x !== $y True if $x is not identical to $y
identity
The following example will show you these array operators in action:

Example

Run this code »


<?php
$x = array("a" => "Red", "b" => "Green", "c" => "Blue");
$y = array("u" => "Yellow", "v" => "Orange", "w" => "Pink");
$z = $x + $y; // Union of $x and $y
var_dump($z);
var_dump($x == $y); // Outputs: boolean false
var_dump($x === $y); // Outputs: boolean false
var_dump($x != $y); // Outputs: boolean true
var_dump($x <> $y); // Outputs: boolean true
var_dump($x !== $y); // Outputs: boolean true
?>

PHP Spaceship Operator PHP 7


PHP 7 introduces a new spaceship operator (<=>) which can be used for
comparing two expressions. It is also known as combined comparison operator.
The spaceship operator returns 0 if both operands are equal, 1 if the left is
greater, and -1 if the right is greater. It basically provides three-way comparison
as shown in the following table:

Operator <=> Equivalent

$x < $y ($x <=> $y) === -1


$x <= $y ($x <=> $y) === -1 || ($x <=> $y) === 0

$x == $y ($x <=> $y) === 0


$x != $y ($x <=> $y) !== 0

$x >= $y ($x <=> $y) === 1 || ($x <=> $y) === 0

$x > $y ($x <=> $y) === 1

The following example will show you how spaceship operator actually works:

Example

Run this code »


<?php
// Comparing Integers
echo 1 <=> 1; // Outputs: 0
echo 1 <=> 2; // Outputs: -1
echo 2 <=> 1; // Outputs: 1

// Comparing Floats
echo 1.5 <=> 1.5; // Outputs: 0
echo 1.5 <=> 2.5; // Outputs: -1
echo 2.5 <=> 1.5; // Outputs: 1

// Comparing Strings
echo "x" <=> "x"; // Outputs: 0
echo "x" <=> "y"; // Outputs: -1
echo "y" <=> "x"; // Outputs: 1
?>
What is a Control Structure?

In simple terms, a control structure allows you to control the flow of code
execution in your application. Generally, a program is executed sequentially,
line by line, and a control structure allows you to alter that flow, usually
depending on certain conditions.

Control structures are core features of the PHP language that allow your script
to respond differently to different inputs or situations. This could allow your
script to give different responses based on user input, file contents, or some
other data.

The following flowchart explains how a control structure works in PHP.

As you can see in the above diagram, first a condition is checked. If the
condition is true, the conditional code will be executed. The important thing to
note here is that code execution continues normally after conditional code
execution.

Let's consider the following example.


In the above example, the program checks whether or not the user is logged
in. Based on the user's login status, they will be redirected to either
the Login page or the My Account page. In this case, a control structure
ends code execution by redirecting users to a different page. This is a crucial
ability of the PHP language.

PHP supports a number of different control structures:

• if
• else
• elseif
• switch
• while
• do - while
• for
• foreach
• and more

Let's take a look at a few of these control structures with examples.


Go Through the Different Control Structures

In the previous section, we learned the basics of control structures in PHP and
their usefulness in application development. In this section, we'll go through a
couple of important control structures that you'll end up using frequently in
your day-to-day application development.

If

The if construct allows you to execute a piece of code if the expression


provided along with it evaluates to true.

Let's have a look at the following example to understand how it actually works.

1 <?php
2 $age = 50;
3
4 if ($age > 30)
5 {
6 echo "Your age is greater than 30!";
}
7 ?>
8
The above example should output the Your age is greater than
30! message since the expression evaluates to true. In fact, if you want to
execute only a single statement, the above example can be rewritten as
shown in the following snippet without brackets.

1 <?php
2 $age = 50;
3
4 if ($age > 30)
5 echo "Your age is greater than 30!";
?>
6
On the other hand, if you have more than one statements to execute, you
must use brackets, as shown in the following snippet.

1 <?php
if (is_array($user))
2 {
3 $user_id = isset($user['user_id']) ? $user['user_id'] : '';
4 $username = isset($user['username']) ? $user['username'] : '';
5 // and more statements...
}
6 ?>
7
8

Else

In the previous section, we discussed the if construct, which allows you to


execute a piece of code if the expression evaluates to true. On the other
hand, if the expression evaluates to false, it won't do anything. More often
than not, you also want to execute a different code snippet if the expression
evaluates to false. That's where the else statement comes into the picture.

You always use the else statement in conjunction with an if statement.


Basically, you can define it as shown in the following pseudo code.

1
if (expression)
2 {
3 // code is executed if the expression evaluates to TRUE
4 }
5 else
{
6 // code is executed if the expression evaluates to FALSE
7 }
8
Let's revise the previous example to understand how it works.

01
02 <?php
$age = 50;
03
04 if ($age < 30)
05 {
06 echo "Your age is less than 30!";
07 }
08 else
{
09 echo "Your age is greater than or equal 30!";
10 }
11 ?>
12
So when you have two choices, and one of them must be executed, you can
use the if-else construct.
Else If

We can consider the elseif statement as an extension to the if-


else construct. If you've got more than two choices to choose from, you can
use the elseif statement.

Let's study the basic structure of the elseif statement, as shown in the
following pseudo code.

01
02 if (expression1)
{
03
// code is executed if the expression1 evaluates to TRUE
04 }
05 elseif (expression2)
06 {
07 // code is executed if the expression2 evaluates to TRUE
}
08 elseif (expression3)
09 {
10 // code is executed if the expression3 evaluates to TRUE
11 }
12 else
{
13 // code is executed if the expression1, expression2 and expression3 evaluates to FAL
14 choice
15 }
16
Again, let's try to understand it using a real-world example.

01 <?php
02 $age = 50;
03
if ($age < 30)
04 {
05 echo "Your age is less than 30!";
06 }
07 elseif ($age > 30 && $age < 40)
08 {
echo "Your age is between 30 and 40!";
09 }
10 elseif ($age > 40 && $age < 50)
11 {
12 echo "Your age is between 40 and 50!";
}
13 else
14 {
15 echo "Your age is greater than 50!";
16 }
17 ?>
18
19
20
As you can see in the above example, we have multiple conditions, so we've
used a series of elseif statements. In the event that all if conditions
evaluate to false, it executes the code provided in the last else statement.

Switch

The switch statement is somewhat similar to the elseif statement which


we've just discussed in the previous section. The only difference is the
expression which is being checked.

In the case of the elseif statement, you have a set of different conditions,
and an appropriate action will be executed based on a condition. On the other
hand, if you want to compare a variable with different values, you can use
the switch statement.

As usual, an example is the best way to understand the switch statement.

01 <?php
02 $favourite_site = 'Code';
03
04 switch ($favourite_site) {
05 case 'Business':
echo "My favourite site is business.tutsplus.com!";
06 break;
07 case 'Code':
08 echo "My favourite site is code.tutsplus.com!";
09 break;
10 case 'Web Design':
echo "My favourite site is webdesign.tutsplus.com!";
11 break;
12 case 'Music':
13 echo "My favourite site is music.tutsplus.com!";
14 break;
case 'Photography':
15 echo "My favourite site is photography.tutsplus.com!";
16 break;
17 default:
18 echo "I like everything at tutsplus.com!";
19 }
?>
20
21
22
23
As you can see in the above example, we want to check the value of
the $favourite_site variable, and based on the value of
the $favourite_site variable we want to print a message.

For each value you want to check with the $favourite_site variable, you
have to define the case block. If the value is matched with a case, the code
associated with that case block will be executed. After that, you need to use
the break statement to end code execution. If you don't use
the break statement, script execution will be continued up to the last block in
the switch statement.

Finally, if you want to execute a piece of code if the variable's value doesn't
match any case, you can define it under the default block. Of course, it's not
mandatory—it's just a way to provide a default case.

So that's the story of conditional control structures. We'll discuss loops in PHP
in the next section.

Loops

Loops in PHP are useful when you want to execute a piece of code repeatedly
until a condition evaluates to false. So code is executed repeatedly as long as
a condition evaluates to true, and as soon as the condition evaluates to false,
the script continues executing the code after the loop.

The following flowchart explains how loops work in PHP.


As you can see in the above screenshot, a loop contains a condition. If the
condition evaluates to true, the conditional code is executed. After execution
of the conditional code, control goes back to the loop condition, and the flow
continues until the condition evaluates to false.

In this section, we'll go through the different types of loops supported in PHP.

While Loop

The while loop is used when you want to execute a piece of code repeatedly
until the while condition evaluates to false.

You can define it as shown in the following pseudo code.

1 while (expression)
2 {
3 // code to execute as long as expression evaluates to TRUE
}
4
Let's have a look at a real-world example to understand how the while loop
works in PHP.
01
02 <?php
03 $max = 0;
04 echo $i = 0;
05 echo ",";
echo $j = 1;
06 echo ",";
07 $result=0;
08
09 while ($max < 10 )
10 {
11 $result = $i + $j;
12
$i = $j;
13 $j = $result;
14
15 $max = $max + 1;
16 echo $result;
17 echo ",";
}
18
?>
19
20
If you're familiar with the Fibonacci series, you might recognize what the
above program does—it outputs the Fibonacci series for the first ten numbers.
The while loop is generally used when you don't know the number of
iterations that are going to take place in a loop.

Do-While Loop

The do-while loop is very similar to the while loop, with the only difference
being that the while condition is checked at the end of the first iteration. Thus,
we can guarantee that the loop code is executed at least once, irrespective of
the result of the while expression.

Let's have a look at the syntax of the do-while loop.

1 do
2 {
3 // code to execute
} while (expression);
4
Let's go through a real-world to understand possible use-cases where you can
use the do-while loop.

01 <?php
02 $handle = fopen("file.txt", "r");
if ($handle)
03 {
04 do
05 {
06 $line = fgets($handle);
07
08 // process the line content
09
} while($line !== false);
10 }
11 fclose($handle);
12 ?>
13
14
In the above example, we're trying to read a file line by line. Firstly, we've
opened a file for reading. In our case, we're not sure if the file contains any
content at all. Thus, we need to execute the fgets function at least once to
check if a file contains any content. So we can use the do-while loop
here. do-while evaluates the condition after the first iteration of the loop.

For Loop

Generally, the for loop is used to execute a piece of code for a specific
number of times. In other words, if you already know the number of times you
want to execute a block of code, it's the for loop which is the best choice.

Let's have a look at the syntax of the for loop.

1 for (expr1; expr2; expr3)


2 {
3 // code to execute
}
4
The expr1 expression is used to initialize variables, and it's always executed.
The expr2 expression is also executed in the beginning of a loop, and if it
evaluates to true, the loop code is executed. After execution of the loop code,
the expr3 is executed. Generally, the expr3 is used to alter the value of a
variable which is used in the expr2 expression.

Let's go through the following example to see how it works.


1 <?php
2 for ($i=1; $i<=10; ++$i)
3 {
4 echo sprintf("The square of %d is %d.</br>", $i, $i*$i);
}
5 ?>
6
The above program outputs the square of the first ten numbers. It
initializes $i to 1, repeats as long as $i is less than or equal to 10, and adds
1 to $i at each iteration.

For Each

The foreach loop is used to iterate over array variables. If you have an array
variable, and you want to go through each element of that array,
the foreach loop is the best choice.

Let's have a look at a couple of examples.

01
02 <?php
03 $fruits = array('apple', 'banana', 'orange', 'grapes');
04 foreach ($fruits as $fruit)
{
05 echo $fruit;
06 echo "<br/>";
07 }
08
09 $employee = array('name' => 'John Smith', 'age' => 30, 'profession' => 'Software Enginee
foreach ($employee as $key => $value)
10 {
11 echo sprintf("%s: %s</br>", $key, $value);
12 echo "<br/>";
13 }
14 ?>
15
If you want to access array values, you can use the first version of
the foreach loop as shown in the above example. On the other hand, if you
want to access both a key and a value, you can do it as shown in
the $employee example above.
PHP: Control Structures
Outline

• { } Statement

• if…else

• if…elseif

• switch

• break

• while

• do…while

• for

Making Decisions
• Decision making or flow control is the process of determining the order in which statements
execute in a program

• The special types of PHP statements used for making decisions are called decision making
statements or decision-making structures

{ } Statement
• A command block is a group of statements contained within a set of braces

• Each command block must have an opening brace ( { ) and a closing brace ( } )

statement1;

statement2;

if Statements
• Used to execute specific programming code if the evaluation of a conditional

expression returns a value of TRUE

• The syntax for a simple if statement is:

if (expression)

// do something

Example

<?php

if(isset($_GET["myNumber"])) {

$a = $_GET["myNumber"];


echo “ตัวเลขทีกรอก คือ ".$a;

if(a>10)

่ ค่ามากกวา่่ 10”;
echo “ตวัเลขทีกรอกมี

?>
if...else Statements
• An if statement that includes an else clause is called an if...else statement

• An else clause executes when the condition in an if...else statement evaluates to FALSE

• The syntax for an if...else statement is:

if (expression)
// do something
else
// do another thing

• An if statement can be constructed without the else clause

• The else clause can only be used with an if statement

Example:

<?php
$a =1;
$b = 2;
if($a > $b)
echo “a is greater than b”;
else
echo “a is less than or equal to b”;
?>
• It executes another expression if the first fails

• The syntax for an if..elseif statement is:

if (expression1)
// do something
elseif(expression2)
// do another thing
elseif(expression3)
// do another thing

else // do another thing

Example

<?php
$a =19;
if($a == 1)
echo “one”;
elseif($a == 2)
echo “two”;
elseif($a == 3)
echo “three”;
elseif($a == 4)
echo “four”;
else
echo “more than four”;
?>

Switch Statements
• The same variable is compared with many different values

• The default statement is used if none of the cases are true

• Statements are executed until it sees a break statement

• The syntax for a switch statement is:

switch ($variable_name) {
case valueA:
statements;
break; // optional
case valueB:
statements;
break; // optional
default:
statements;
}

break
• break statement ends execution of the current for, while, do-while or switch structure.

• break accepts an optional numeric argument which tells it how many nested enclosing
structures are to be broken out of

Example

<?php
$a = 2;
switch($a){
case 0:
echo “a equals to 0”;
break;
case 1:
echo “a equals to 1”;
break;
default:
echo “a is greater than 1”;
}
?>

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> </meta>
</head>
<body>
<form action= "switch1.php" method= "GET">
Select a language:
<select name = "myLanguage" >
<option value= "TH"> Thailand </option>
<option value= "EN"> English </option>
<option value= "CH"> Chinese </option>
<option value= "JP"> Japanese </option>
</select>
<input type = "submit" value = "NO">
<hr>
</form>
<?php
if(isset($_GET["myLanguage"])) {
$x = $_GET["myLanguage"];
switch($x) {
case 'TH': echo 'Thailand' ; break;
case 'EN': echo 'English' ; break;
case 'CH': echo 'Chinese' ; break;
case 'JP': echo 'Japanese' ; break;
default: echo 'Invalid' ;
}}
?>
</body>
</html>

while
• It tells PHP to execute the nested statements repeatedly, as long as the while expression
evaluates to TRUE

• If the first evaluation of the statement return FALSE, the while loop will not be executed at all

• The syntax for while statement is:

while (expression){
statement;
statement;
}
Example

<?php
$x=1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>

do...while
• The statement inside the loop will be executed at least once.

• The truth expression is checked at the end of each iteration instead of in the beginning.

• The syntax for an do...while statement is:

do{
statement;
statement;
}while(expression);
<?php
$x=1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5 );
?>

Example

<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>

for
• for loop is used if you know how many times you want to execute the statements

• The syntax for for statement is:

for(initial;condition;inc/dec){
statement;
statement;
}

• The first expression(initial)is evaluated once unconditionally at the beginning of the loop

• In the beginning of each iteration, the second expression (condition)is evaluated. If the

result is True, the loop continues and the nested statements are executed. If the result is

False, the loop ends.

• At the end of each iteration, the third expression (increment/decrement) is evaluated.


Example

<?php
for($i = 1; $i < 10; $i++) {
echo "The number is $i ";
}
?>
Applications Development and
Emerging Technologies
MODULE 2, SUBTPOPIC 1

PHP Operators
PHP Operators and Control Structures

Objectives
• To understand the different types of operators that are
available on PHP.
• To know what is operator precedence and operator
associativity in PHP.
• To ensure that programs expression are logically correct by
using the correct referencing values of its precedence.
• To use escape sequence properly in the program.
PHP Operators and Control Structures

Operators
An operator is a symbol that specifies a particular action in an expression

Operator Precedence, Associativity, and Purpose


PHP Operators and Control Structures

Operator Precedence, Associativity, and Purpose

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.124
PHP Operators and Control Structures

Operator Precedence
is a characteristic of operators that determines the order in which they
evaluate the operands surrounding them.

Output:
PHP Operators and Control Structures

Operator Associativity
is a characteristic of an operator specifies how operations of the same
precedence are evaluated as they are executed.

Output:

Example:
PHP Operators and Control Structures

Arithmetic Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.124

Assignment Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.126
PHP Operators and Control Structures

Increment and Decrement Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.127

Example: Output:
PHP Operators and Control Structures

Comparison Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.129

Example: Output:
PHP Operators and Control Structures

Logical Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.128
Equality Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.129
PHP Operators and Control Structures

Bitwise Operator

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.130

Example: Output:
PHP Operators and Control Structures

Escape Sequences

Beginning PHP and MySQL 3rd Edition by: W. Jason Gilmore pp.132
PHP Operators and Control Structures

Summary
• Simplifying expression needs to follow a general precedence set by
PHP scripts.
• An operator specifies a particular action in a given expression.
• Available PHP operators are arithmetic, conditional, assignment,
logical and bitwise operator.
• Operator precedence characteristics determines the order in which
they evaluate the operands surrounding them.
• Operator associativity characteristic specifies how operations of the
same precedence are evaluated as they are executed.
• Post increment or decrement always execute the statement first
before incrementing or decrementing the value of a given variable.
• Pre increment or decrement always increment or decrement its
variable value before executing the statement.
• Escape sequence has its own special task in executing the string
as an output.
Applications Development and
Emerging Technologies
MODULE 2, SUBTOPIC 2

PHP Control Structures


PHP Operators and Control Structures

Objectives
• To know the different approach of control structures.
• To know the fundamentals syntax for conditional and
looping structures.
• To properly use the compound expression using the logical
operators.
• To know the rules of break, continue, and goto statements.
• To see some alternative enclosure for control structures.
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements

if statement
syntax: elseif statement
if(expression) { syntax:
statement… if(expression) {
} statement…
}
else statement elseif(expression) {
syntax: statement…
if(expression) { } else {
statement… statement…
} else { }
statement
}
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Example:
Output:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Nested if…else

Output:
Example:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Compound expression using logical operators

Output:
Example:
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


switch statement
syntax:
switch($category){
case opt1:
statement…
break;
case opt2:
statement…
break;
case opt3:
statement…
break;

default:
statement…
}
PHP Operators and Control Structures

PHP Control Structures: Conditional Statements


Switch Statement

Example: Output:
PHP Operators and Control Structures

PHP Control Structures: Looping Statements

while statement for statement


syntax: syntax:
while(expression){ for(expr1;expr2;expr3)
statement… {
} statement…
}
do … while statement
syntax:
do{
statement…
}while(expression);
PHP Operators and Control Structures

PHP Control Structures: Looping Statements

Example: Output:
PHP Operators and Control Structures

PHP Control Structures: break, continue,


and goto statement

break
break statement is placed within the code of a loop to cause
the program to break out of the loop statement.

continue
continue statement causes execution of the current loop
iteration to end and commence at the beginning of the next iteration.

goto … label:
goto statement is used to jump to other section of the
program to support labels.
PHP Operators and Control Structures

PHP Control Structures: break, continue,


and goto statement

Example:
Output:
PHP Operators and Control Structures

PHP Control Structures: alternative enclosure syntax

Involves replacing the opening bracket with a colon(:) and


replacing the closing bracket with endif;, endwhile;,endfor;,
endswitch

Example: Output:
PHP Operators and Control Structures

Summary
• Conditional statements are statement the will execute statement
inside a block if a given condition is true
• Use compound expression to minimize the process of coding using
nested if statement.
• break statement caused the program to break if used.
• continue statement end the current loop and continue to next
iteration.
• goto statement used to jump to other section of the program.
• Alternative enclosure syntax is available for if, while, for, foreach,
and switch control.

You might also like