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

SEN 102 Computer Programming I - Week 2

The document outlines the principles of programming, focusing on control structures in PHP, including conditional statements (if, if-else, switch, match) and loops (while, do-while, for, foreach). It explains how these structures allow for decision-making and repetitive tasks in programming. Examples and syntax for each type of control structure are provided to illustrate their usage.

Uploaded by

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

SEN 102 Computer Programming I - Week 2

The document outlines the principles of programming, focusing on control structures in PHP, including conditional statements (if, if-else, switch, match) and loops (while, do-while, for, foreach). It explains how these structures allow for decision-making and repetitive tasks in programming. Examples and syntax for each type of control structure are provided to illustrate their usage.

Uploaded by

Doctor krystyne
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/ 36

Week 2

SEN 102 Principles


of Programming I
Software Engineering,
Department of Computing Science,
Faculty of Science,
Admiralty University of Nigeria (ADUN),
Delta State.

Lecturer: Bernard Ephraim


Control Structures: Conditional Statements
& Loops
What are Control Structures?
 Control Structures are at the core of programming
logic. They allow a script to react differently depending
on what has already occurred, or based on user input,
and allow the graceful handling of repetitive tasks.
 In PHP, there are two primary types of Control
Structures:
1. Conditional Statements and
2. Control Loops
Conditional Statements
Conditional Statements
 Conditional statements are statements that allow us to
execute a particular block of code once if a condition is met.
 There are different kinds of conditional statement:
1. If statements
2. If…else statements
3. If…elseif…else statements
4. Switch statements
5. Match statement
If statements
 This is the basic form of conditional statements.
 Its usage is based on the common day-to-day usage of if statements in natural
language.
 For instance, you can tell your friend to get a you a bottle of coke if it is chilled.
 In the case above if your friend finds out from the seller that his stock of coke
drink is not chilled, he is obliged not to buy.
 The following syntax is used to infer the if statement in PHP and most
programming languages
if (condition) {
code to be executed if condition is true;
}
If statements cont’d
 The condition in the example above is the state of the coke drink being child
 Hence we can represent this condition by is_chilled?
if (isChilled){
//get coke
}
 Example
$isChilled = true;
if($isChilled){
echo 'get coke';
}
If…else Statements
 When we critically look at most use-cases of the if statement in natural language an alternative is
usually provided when the condition is not met.
 In our example above, you could ask your friend to get you ice-scream instead of available coke is
not chilled.
 This would be like this in plain English “get me a bottle of coke if it is chilled else get me one bottle
water”.
 Notice the use of else – this is similar in the case of PHP and other programming languages
$isChilled = false;
if($isChilled){
echo 'get coke';
}else{
echo 'get one bottle water';
}
If…elseif…else Statements $isChilled = false;
 What if you have more than one $isBiscuitAvailable=false;
alternative for the chilled coke? if($isChilled){
Then you find yourself telling the
echo 'get coke';
your friend a series of or else if or
else if statement. }elseif($isBiscuitAvailable){
 For example this would tell your echo 'get one bottle water and
friend to get chilled coke or a biscuit';
bottle of water and biscuit if biscuit }else{
is available else candy.
echo 'get candy';
}
If…elseif…else Alternate Syntax Example
 An alternate syntax for the if $a=5;
statement is to replace the opening if ($a == 5):
curly brackets ,{, with colon ,:, and
echo "a equals 5...";
end the if statement with the
endif; and a semi-colon. elseif ($a == 6):
 This can be useful in conditionally echo "a equals 6!!!";
outputting html within php else:
statement
echo "a is neither 5 nor 6";
$a=5;
endif;
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
Switch
 Its syntax is:  alternative syntax:
 The switch statement is similar to a
series of IF statements on the same switch ($variable) { switch ($variable):
expression.
case 'value': case 'value':
 In many occasions, you may want to
compare the same variable (or # code... # code...
expression) with many different values, break; break;
and execute a different piece of code
depending on which value it equals to. default: default:
 This is exactly what the switch statement # code... # code...
is for.
break; break;
 It is a special case of the if…elseif
statement and often cleaner form of } endswitch;
expression.
 Example
Switch Cont’d
switch (1) {
 In the sample code above, the
variable $variable is compared with case 1:
the values appended to the case echo '1';
statement.
case 2:
 If a match is found the code starts
executing from that point downwards echo '2';
through the whole switch statement. case 3:
echo '3';
}
 Example
Switch Cont’d
switch (1) {
 One use case for this continuous
downward execution of code could case 1:
be when two or more case conditions case 2:
have the same implementation then
stacking the cases together would echo '2 and two';
help prevent repeating yourself }
 Example
Switch Cont’d
switch (1) {
 To prevent this continuous downward
case 1:
execution of code from happening
echo '1';
we use the break statement at the
end of every case block break;
case 2:
echo '2';
break;
case 3:
echo '3';
break;
}
 Example
Switch Cont’d switch (10) {
 When no match is found a default case 1:
block can be defined to be executed echo '1';
according to your need break;
case 2:
echo '2';
break;
case 3:
echo '3';
break;
default:
echo 'default';
break;
}
$x = 2;
Switch Cont’d switch ($x+1) {
 Both the switch condition and the case 1:
case match can be expressions echo '1';
break;
case 2:
echo '2';
break;
case 3:
echo '3';
break;
default:
echo 'default';
break;
}
Match
 The match expression branches evaluation based on an identity check of a value.
 Similarly to a switch statement, a match expression has a subject expression that is
compared against multiple alternatives.
 Unlike switch, it will evaluate to a value much like ternary expressions.
 Unlike switch, the comparison is an identity check (===) rather than a weak equality
check (==).
 Match expressions are terminated with a semi-colon
 Syntax,
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
Match Cont’d
 Example,
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
Match Cont’d
 The list of options in the matches must be exhaustive.
 The code below will produce an UnhandledMatchError error, since the value of
food equal to beans does not exist in the match list
$food = 'beans';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
Match Cont’d
 To solve this problem, just as in the switch statement use the default statement
to handle no matched cases.
$food = 'beans';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
default=>'no match found'
};
var_dump($return_value);
 Example
Match Cont’d
$food = 'lime';
 When the implementation of one or
more matches is the same the match $return_value = match ($food) {
expression can be separated by commas 'apple' => 'This food is an apple',
and the implication sign pointing to the
common expression they evaluate to: 'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
'orange','lemon','lime' => 'This is a kind
of citrus',
default=>'no match found'
};
var_dump($return_value);
 Example
Match Cont’d
$age = 13;
 You can also match a Boolean true or
false with the outcome of an expression $result = match (true) {
that evaluate to the Boolean type. $age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
Switch Vs Match
 The match expression is similar to a switch statement but has some key
differences:
1. A match arm compares values strictly (===) instead of loosely as the
switch statement does.
2. A match expression returns a value.
3. match arms do not fall-through to later cases the way switch
statements do.
4. A match expression must be exhaustive.
Control Loops
Control Loops
 Loops in PHP and other programming languages are control structures
used to execute the same block of code a specified number of times.
 Some control loops cause a repeated execution of a specified block of
codes while a condition remains true thus called while and do-while
loops.
 Others cause the repetition over a specified number of counts hence
the name for loop.
 Another causes repetition over the iteration items in an array or array-
like structures hence, foreach loop.
While Loops
 These loops cause the repeated execution of a nested block of code
given that a condition holds true.
 It tells PHP to execute the nested statement(s) repeatedly, as long as the
while expression evaluates to true.
 Its syntax:  Alternate syntax:
while (expr){ while (expr):
statement statement
... ...
} endwhile;
While Loops Cont’d
 For example, we can display the count from
value 1 until x is greater than 10
$x = 0;
while($x <= 10){
echo $x;
$x = $x + 1;
}
While Loops Cont’d Example
 Note: to avoid having an infinite loop $x = 0;
(that is, a loop that runs for ever) while($x <= 50){
ensure you have a way of modifying the if($x == 45) {
condition the while statement depends
on such that a logical termination of break;
the loop can be attained; }
 To terminate and exit a while loop or echo $x;
other kinds of control loops $x = $x + 1;
prematurely use the break; statement
as seen: }
Do-While Loops Example
 Similar to the while loop but differ in $x = 0;
the sense that the code block to be do{
repeated is executed at least once echo $x;
before evaluating the conditional
statement. $x = $x + 1;
 Thus, the statement is executed at least }while($x >= 50);
once whether the condition evaluates
to true or false.
For Loops Example
 This loops repeats a block of code until for ($i = 1; $i <= 10; $i++) {
a certain condition is met
echo $i;
 The loop works by counting from a
initial value (expr1) and incrementing it }
based on a defined expression (expr3)
until it reaches a predefined value
(expr2) at which the loop is terminated.
 On each count the code in the loop is
executed
for (expr1; expr2; expr3){
statement
}
For Loops Cont’d
 To create an infinite for loop just replace the three expressions with
spaces.
Example
for ( ; ; ) {
echo 'yes';
}
For Loops Cont’d Correct Way:
 While expressions are allowed to $people = array(

be used as arguments to the for array('name' => 'Kalle', 'salt' => 856412),
loops, the cost of evaluating this array('name' => 'Pierre', 'salt' => 215863)
expressions should not be );
expensive $size = count($people);
for($i = 0, $i < $size; ++$i) {
 Wrong way:
$people[$i]['salt'] = mt_rand(000000, 999999);
$people = array(
}
array('name' => 'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
Foreach Loops
 The foreach construct provides an easy way to iterate over arrays.
 foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable.
 There are two syntaxes:
foreach (iterable_expression as $value){
statement
}
foreach (iterable_expression as $key => $value){
statement
}
Foreach Loops Cont’d
Unsetting A Variable:
 Example
$arr = array(1, 2, 3, 4);
$arr = array(1, 2, 3, 4);
foreach ($arr as $key => $value) {
foreach ($arr as $key =>
echo "{$key} => {$value}, "; $value) {
} echo "{$key} => {$value}, ";
 Note: that the variable $value has its last value
retained even after exiting the foreach loop.
}
 This can become a problem when passing that unset($value);
argument by reference as any modification to the
variable leads to modifications in the array. echo $value;
 Solution is to unset the variable $value after exiting
the foreach loop
Foreach Loops Cont’d $array = [
 Unpacking Nested Arrays With list() [1, 2],
 It is possible to iterate over an [3, 4],
array of arrays and unpack the ];
nested array into loop variables foreach ($array as list($a, $b)) {
by providing a list() as the value. // $a contains the first element of the nested array,
 For example: // and $b contains the second element.

echo "A: $a; B: $b\n";


}
Questions & Answers

You might also like