Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
253 views

ITE 311 - Unit 3 Conditional Statements, Looping and Array

This document discusses conditional statements, looping, and arrays in PHP for a web systems development course. It covers if, elseif, else statements; nested if statements; switch statements; and using loops and arrays. Examples are provided to demonstrate evaluating conditions and comparing values to determine program flow. The benefits of conditional logic and repetition through looping and arrays for web development are also mentioned.

Uploaded by

Ron Marasigan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
253 views

ITE 311 - Unit 3 Conditional Statements, Looping and Array

This document discusses conditional statements, looping, and arrays in PHP for a web systems development course. It covers if, elseif, else statements; nested if statements; switch statements; and using loops and arrays. Examples are provided to demonstrate evaluating conditions and comparing values to determine program flow. The benefits of conditional logic and repetition through looping and arrays for web development are also mentioned.

Uploaded by

Ron Marasigan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

ITE 311 - Web Systems and Development

Unit 3 Conditional Statements, Looping and Array

A. LEARNING OUTCOMES:
1. Defined what are the conditional statements available in PHP.
2. Practiced to create simple scripts using arrays and looping.
3. Understood the benefits of using loops and arrays in actual web system development.

B. PRE-TEST
Multiple Choice: Write only the letter (UPPERCASE LETTER) that corresponds to your answer.
________1. Use to execute a block of code only if the specified condition evaluates to true.
a. Looping
b. Condition
c. If statement
d. Elseif statement
________2. Which statement is correct?
a. if ($x == 0) echo ‘x is equal to 0;
b. $x+;
c. $x--;
d. a and c
________3. Which statement is correct?
a. if ($x == 0) echo ‘x is equal to 0;
b. $x+;
c. $x--; $x is less than 1
d. None of these
________4. It extends an if statement to execute a single statement or a group of statements if a certain condition is met.
a. looping
b. elseif
c. else
d. None of these
________5. It means if block inside another if block.
a. looping
b. nested if
c. else
d. None of these
________6. It is like the else from if
a. break
b. nested if
c. default
d. None of these
________7. Use to get out of the Switch statement
a. break
b. nested if

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
c. default
d. None of these
________8. It is used before each value you want to check for in switch statement.
a. break
b. nested if
c. default
d. None of these
________9. It provides a shorthand way of writing the if...else statements.
a. NullCoalescing
b. nested if
c. default
d. Ternary Operator
________10. It should be used when we know how many times a task is to be repeated.
a. For loop
b. While loop
c. Do while
d. Ternary Operator

C. CONTENT
IF STATEMENT
The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest
PHP's conditional statements and can be written like:

The following example will output "Have a nice weekend!" if the current day is Friday:

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
IF ELSE STATEMENT
You can enhance the decision-making process by providing an alternative choice through adding an else statement to
the if statement. The if...else statement allows you to execute one block of code if the specified condition is evaluates to true
and another block of code if it is evaluates to false. It can be written, like this:

 
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 following example will output "Have a nice weekend!" if the current day is Friday, otherwise it will output "Have a nice day!"

Example:
Write a conditional statement that will evaluates if a person is a senior citizen or not.

In this example we assigned $age variable to hold the age of the person. We use if statement to check if the age is greater than
or equal to 60 to see if he is a senior citizen.
 

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
ELSE IF STATEMENT
Elseif is a combination of if and else. It extends an if statement to execute a single statement or a group of statements
if a certain condition is met. It cannot do anything if the condition is false.

Example:
Write a program that will evaluate the largest number between three (3) numbers
.
 

In this example we assumed that $a, $b and $c hold the three (3) numbers to compare. Using if...elseif...else
statements we compare each variable to check the largest. If no condition matched, it means that the value of the
variables is equal.
Tips:
 Use indenting to make code clearer.
 Code most likely conditions first
 Code positive conditions where possible
 Code parts of solution executed most often first

NESTED IF STATEMENT
A control structure inside another control structure. The ability to nest, or embed, several if statements within one
another provides the ultimate level of control in evaluating expressions.

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development

This is the syntax of nested if statement.


You can have additional if statement
inside another if statement.

Example:
Suppose we wanted to evaluate the cooking weight only if the food in question was pasta:

As you can see from the preceding code listing, nested if statements provide you with greater control over the
flow of your program. As your programs grow in size and complexity, you will find nested control statements an
indispensable programming tool.

SWITCH STATEMENT
The switch-case statement is an alternative to the if-elseif-else statement, which does almost the same thing. The
switch-case statement tests a variable against a series of values until it finds a match, and then executes the block of code
corresponding to that match.

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development

 Control program flow by executing a specific set of statements depending on the value of an expression
 Compare the value of an expression to a value contained within a special statement called a case label
 A case label is a specific value that contains one or more statements that execute if the value of the case label matches the
value of the switch statement’s expression
Consist of the following components:
o The switch keyword
o An expression
o An opening brace
o One or more case labels
o The executable statements
o The break keyword
o A default label
o A closing brace

A case label consists


o The keyword case
o A literal value or variable name
o A colon (:)
o A case label can be followed by a single statement or multiple statements
o Multiple statements for a case label do not need to be enclosed within a command block

The default label contains


o Statements that execute when the value returned by the switch statement expression does not
match a case label
o A default label consists of the keyword default followed by a colon (:)

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
Consider the following example, which display a different message for each day.

The switch-case statement differs from the if-elseif-else statement in one important way. The switch statement
executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it's not only
executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of
the switch block automatically.
To prevent this, add a break statement to the end of each case block. The break statement tells PHP to break out of
the switch-case statement block once it executes the code associated with the first true case.

 
Tips:
 The switch statement is easy to edit as it has created
the separate cases for different statements whereas, in
nested if-else statements it becomes difficult to identify
the statements to be edited.

TERNARY OPERATOR
The ternary operator provides a shorthand way of writing the if...else statements. The ternary operator is represented
by the question mark (?) symbol and it takes three operands: a condition to check, a result for true, and a result for false.

  To understand how this operator works, consider the following examples:

Using the ternary operator, the same code could be written in a more compact way:

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development

The ternary operator in the example above selects the value on the left of the colon (i.e. 'Child') if the condition evaluates to true
(i.e. if $age is less than 18), and selects the value on the right of the colon (i.e. 'Adult') if the condition evaluates to false.

Tips:
 Code written using the ternary operator
can be hard to read. However, it provides
a great way to write compact if-else
statements.

NULL COALESCING OPERATOR


PHP 7 introduces a new null coalescing operator (??) which you can use as a shorthand where you need to use a
ternary operator in conjunction with isset() function.
To understand this in a better way consider the following line of code. It fetches the value of $_GET['name'], if it does
not exist or NULL, it returns 'anonymous'.

Using the null coalescing operator, the same code could be written as:

As you can see the later syntax is more compact and easier to write.

LOOP STATEMENTS
A loop statement is a control structure that repeatedly executes a statement or a series of statements while a specific
condition is TRUE or until a specific condition becomes TRUE.
There are four types of loop statements:
o while statements
o do...while statements
o for statements
o foreach statements

FOR LOOP
For loops should be used when we know how many times a task is to be repeated. These are also called as counting
loops, as they count the number of times the loop runs. It is useful to know that a for loop can be written as a while loop, but
vice-versa is not true.
 Combine the initialize, conditional evaluation, and update portions of a loop into a single statement
 Repeat a statement or a series of statements as long as a given conditional expression evaluates to TRUE
 If the conditional expression evaluates to TRUE, the for statement executes and continues to execute repeatedly until
the conditional expression evaluates to FALSE.

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development

In for loop, a loop variable is used to control the loop. First initialize this loop variable to some value, then check
whether this variable is less than or greater than counter value. If statement is true, then loop body is executed and loop
variable gets updated. Steps are repeated till exit condition comes.

o Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 1;
o Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute
the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 10;
o Update Expression: After executing loop body this expression increments/decrements the loop variable by some value.
for example: $num += 2;
 

Example:

Output:

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
Exercises:

1. Write a program in PHP to display the first 10 natural numbers.


Expected Output :
The first 10 natural numbers are: 1 2 3 4 5 6 7 8 9 10
Answer:

2. Write a C program to find the sum of first 10 natural numbers.


Expected Output :
The first 10 natural numbers are : 1 2 3 4 5 6 7 8 9 10 The Sum is : 55

  Answer:

WHILE LOOP
The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop and if
it’s true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds
true.
 Each repetition of a looping statement is called an iteration
 A while statement keeps repeating until its conditional expression evaluates to FALSE
 A counter is a variable that increments or decrements with each iteration of a loop statement
 In an infinite loop, a loop statement never ends because its conditional expression is never FALSE

Example:
Prepared by: Ronald M. Marasigan
ITE 311 - Web Systems and Development
:

Output:

Exercises:

1. Write a PHP program to find all even numbers between 10 and 20.
Expected Output :
Even numbers are : 10 12 14 16 18 20
Answer:

DO WHILE LOOP
Prepared by: Ronald M. Marasigan
ITE 311 - Web Systems and Development
The while loop - Loops through a block of code as long as the specified condition is true.
This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the
condition. Therefore, a statement is executed at least once on using the do…while loop. After executing once, the program is
executed as long as the condition holds true.
Example:

Output:

PHP ARRAYS
An array lets you store multiple values for a variable in a single association. For instance, let’s say we want to have
many varieties of fruit. You could have an array of fruit, whose values could be any one of apples, oranges, grapes, or pears.
 A data structure to express a collection of related values
 Associates each value in the array with a key
 Not only like other languages’ arrays, but it is also like their vector, hash table, dictionary, and list collections

Keys
o Must be either integers or strings but need not be sequential
o Cannot use an array or object as a key
Values
o Can be any object, type, or primitive supported in PHP (not restricted to integers and strings), including arrays
o You can even have objects of your own types

There are three main types of arrays:

o indexed array
Prepared by: Ronald M. Marasigan
ITE 311 - Web Systems and Development
o associative arrays
o multidimensional array

Indexed Arrays

All arrays have 2 components to each item within the array: key and value. The key is like a bookmark that makes the
value of the item easy to locate. In an indexed array, the “key” portion of the array item is always an integer (whole
number). This way we can let PHP automatically assign numeric keys to each array item in the order that the values are
assigned.

For instance, if we use our fruit example from above, we could declare a new array called $fruit and
immediately assign values to the array like this:

$fruit = array("apples","oranges","grapes","pears");

What this does is create an array called $fruit, and assign the keys and values as follows:

Notice how the “first” numeric key we see assigned is “0.” It is very important to understand that computers like to start
counting at 0 (zero). So even though there are 4 items in the array listed above, the numeric keys range from 0-3.
Don’t let this trip you up in your logic; just remember that arrays start the count at 0.
Inspecting Array
So in the $fruit example above, you can see the keys and values because we outlined them in a table for
demonstration purposes. But how could you get this information through PHP?

There is a function that we use to inspect arrays so that you can see exactly what’s inside of them:

print_r()

So let’s say we already declared our $fruit array as listed above. If we use “print_r()” on the $fruit
array, it will display all of the items’ keys and respective values:

print_r($fruit);

…will return to the browser:

Array ( [0] => apples [1] => oranges [2] => grapes [3] => pears )

In addition to creating an indexed array as we saw above, you can also create the same array of fruit by deliberately assigning
values to each numeric index key. See below:
Prepared by: Ronald M. Marasigan
ITE 311 - Web Systems and Development

In fact, we could at any time add a new item to an array simply by declaring it anywhere in the php:

$fruit[4] = "kiwi";

This would add the “kiwi” value to the fourth position of the array.

Associative Arrays

An associative array is different from an indexed array in that the associative type can hold other data types for its keys
besides integers. With an associative array, we can pair information in a way that associates the key to value so that the
array is more informative to us than an indexed type.

If we use the last example of the indexed array, $employee, you realize that we have no idea what those values
represent, other than positions 0-6 of the array. But if we make it an associative array, the representations become more
evident:

If you inspect this array with <pre></pre> tags around the print_r() function, it will print this to the browser:

$employee = array(
[firstname] => “Tom”
[lastname] => “Robertson”
[age] => 21
[payrate] => 13.5
[sex] => “male”
[position] => “cashier”
[years_service] => 2.5
)

Notice that the keys are in brackets instead of quotes now. Remember, data wrapped in square brackets like
this indicates that it is a key in an array. Also notice that the commas are gone after each line, and that it doesn’t

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
display our terminator at the end. I am pointing this out in the event you try to copy and paste the code to make it work
as an array definition; it won’t work. You will need to copy the php code that DEFINES the array, not the output of the
print_r() function.

Multidimensional Arrays

Now that we have a concept of how indexed and associative arrays work, let’s briefly look at multidimensional arrays. I
say “briefly” because these are a little bit more advanced, and it might take a little bit of practical application later before you
fully grasp the concept of how they are useful. So don’t worry if you don’t completely get it right now!

Basically, a multidimensional array is simply an array that contains at least one other array in is as a value. Sometimes
you need to hold more complex sets of data in a single variable than just an associative array. Let’s look back to the $fruit
example to see one way of thinking about it.

Instead of calling out just apples, oranges, grapes, and pears, let’s say we need to hold more information about the
fruit types, like “citrus, melons, berries.” We could do this:

The top-level array is like an associative one, whose key => value pair holds two critical pieces of information, but the
value of each item in the top level array happens to contain MULTIPLE values. So we have to assign a new array to each
fruit type’s value. In the example above, we have indexed arrays nested inside of a top level associative-structure; the net
result is that the entire package is a “multidimensional array.”

We could even take it a step further if we wanted and include the information about how each fruit grows. Take a look:

FOREACH LOOP

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
PHP 4 introduced "foreach" construct, it works only on arrays. The foreach looping is the best way to access each
key/value pair from an array.

array_expr is an array. In every loop the value of the current element of the array is assigned to $value and the internal array
pointer is advanced by one and the process continue to reach the last array element.
foreach (array_expr as $key => $value)
{
//statement
}
array_expr is an array. In every loop the current element's key is assigned to $key and the internal array pointer is advanced
by one and the process continue to reach the last array element.

Example 1:
In the following example, we define an array with five elements and later we use foreach to access array
element's value.

Output:

Example 2:

Prepared by: Ronald M. Marasigan


ITE 311 - Web Systems and Development
In the following example, both the keys and values of an array have accessed (see the second syntax of the
foreach statement).

Output:

D. LEARNING ACTIVITIES
Reflection Paper Writing and Publishing
Directions: Think of a game that you want to create using conditional statements. Record a video and discuss the game ideas
and mechanics you have chosen.
Submit your work to google class on or before the date as reflected in in your study schedule. See Rubric in Blogging in
the classwork.
E. ASSESSMENT

I – MUTIPLE CHOICE: Write only the letter (UPPERCASE LETTER) that corresponds to your answer.

_ ____1. Which statement is a converse statement of the conditional statement: If the apple is bright, then the apple is fresh.

a) If the apple is not bright then the apple is not fresh

b) If the apple is fresh then the apple is bright

c) If the apple is fresh then the apple is red

d) None of these

_ ____ 2. How many choices are possible when using a single if-else statement?

a) 1

b) 2

c) 3

d) 4

_ ____ 3. What does the following code fragment write to the monitor?
$sum = 14; Prepared by: Ronald M. Marasigan

if ( $sum < 20 )
ITE 311 - Web Systems and Development

a) Under

b) Over

c) Under the limit

d) Over the limit

____ 4. What kind of statement is an If statement?

a) Comparison

b) Logical

c) Conditional

d) Anecdotal

_ ____ 5. What happens when an If statements conditional is not true?

a) The If statement starts over

b) The If statement executes

c) Nothing happens

d) None of these

_ ____ 6. What is the inverse of the statement “If Mike did his homework, then he will pass this test”?

a) If Mike passes this test, then he did his homework.

b) If Mike does not pass this test, then he did not do his homework.

c) If Mike does not pass this test, then he only did half his homework.

d) If Mike did not do his homework, then he will not pass this test.

_ ____ 7. Given the true statement: “If a person is eligible to vote, then that person is a citizen.” Which statement must also be
true?

a) Kayla is not a citizen; therefore, she is not eligible to vote.

b) Juan is a citizen; therefore, he is eligible to vote.

c) Marie is not eligible to vote; therefore, she is not a citizen.

d) Morgan has never voted; therefore, he is not a citizen.

_ ____ 8. Which statement is the converse of “If the sum of two angles is 180°, then the angles are supplementary”?

a) If two angles are supplementary, then their sum is 180°.


Prepared by: Ronald M. Marasigan
ITE 311 - Web Systems and Development
b) If the sum of two angles is not 180°, then the angles are not supplementary.

c) If two angles are not supplementary, then their sum is not 180°.

d) If the sum of two angles is not 180°, then the angles are supplementary.

_ ____ 9. Which statement is the converse of “If the sum of two angles is 180°, then the angles are supplementary”?

a) I pass the test if I study.

b) If I do not study, then I do not pass the test.

c) If I do not pass the test, then I do not study.

d) If I pass the test, then I study

_ ____ 10. What is the converse of the statement "If it is Sunday, then I do not go to school"?

a) If I do not go to school, then it is Sunday.

b) If it is not Sunday, then I do not go to school.

c) If I go to school, then it is not Sunday.

d) If it is not Sunday, then I go to school.

  II – TRUE or FALSE: Write T if the statement is true, otherwise write F.

_____ 1. If statement in PHP always needs brackets.

_____ 2. A double negation is the same thing as no negation.

_____ 3. && means OR.

_____ 4. If statement has default keyword.

_____ 5. You can put another if statement inside an if statement.

III – IDENTIFICATION: Identify the answer in the following questions.

____________________ 1. It is used to execute a block of code only if the specified condition evaluates to true.

____________________ 2. Allows you to execute one block of code if the specified condition is evaluates to true and another
block of code if it is evaluates to false.

____________________ 3. A control structure inside another control structure.

____________________ 4. It's used when there could be other, unknown, options.

____________________ 5. Use this to get out of the Switch statement.

Prepared by: Ronald M. Marasigan

You might also like