Week 4
Week 4
Web Programming
Week4:- Expressions & Control flow in PHP
Expressions
• An expression is a combination of values, variables, operators, and functions
that results in a value.
• Syntax
if(condition){
code to be executed if condition is true;
}
Example
date() is a predefined function which formats a local date and time, and returns the
formatted date string.
else statement
• Sometimes when a conditional is not TRUE, you may not want to
continue on to the main program code immediately but might wish to
do something else instead.
• This is where the else statement comes in
else statement[2]
• With an if ... else statement, the first conditional statement is
executed if the condition is TRUE.
• But if it’s FALSE, the second one is executed
• Syntax
if(condition){
}
else{
}
Example
Activity 4.1
• Write down a PHP code segment to display whether a given number is
odd or even.
elseif Statement
• There are also times when you want a number of different
possibilities to occur, based upon a sequence of conditions.
• But as the number of elseif statements increases, you would probably be better
advised to consider a switch statement if it fits your needs.
• Syntax
if(condition){
}elseif(condition){
}else{
}
Example
The switch Statement
• The switch statement is useful in cases in which one variable or the result of an expression can
have multiple values, which should each trigger a different function.
• Often you may want a program to repeat the same sequence of code
again and again until something happens, such as a user inputting a
value or reaching a natural end.
while(condition){
//statement
increment/decrement
}
Activity 4.4
• Write down a PHP code segment to display the numbers from 10-1.
Example
do……while loop
• Syntax
do{
//statement
increment/decrement
}while(condition);
Example
Activity 4.6
• Write down a PHP code to display the numbers from 1-10
For loop
• The for loop, is also the most powerful, as it combines the abilities to
set up variables as you enter the loop, test for conditions while
iterating loops, and modify variables after each iteration.
• Syntax
for(initialization; condition; increment/decrement){
//statement
}
Example
Activity 4.6
• Write a small PHP code to print multiplication table of 5.
5 times 1= 5
5 times 2=10
……………
………….
………
For loop[2]
• A more complex form of the for statement even lets you perform
multiple operations in each of the three parameters
• Example
Break
• Just as you saw how to break out of a switch statement, you can also
break out of a for loop using the same break command.
Continue
• The continue statement is a little like a break statement, except that it
instructs PHP to stop processing the current loop and to move right to
its next iteration.
Questions ?
Thank You !