Date post: | 02-Jul-2015 |
Category: |
Technology |
Upload: | kristophorus-hadiono |
View: | 654 times |
Download: | 2 times |
Control Statement
PHP - TUTORIAL
Selection
●IF●IF … ELSE●ELSEIF●SWITCH
Selection - IF●IF <expression>
statement-true;
●ex.
$name=”kris”;
IF ($name==”kris”)echo “Welcome Kris.”;
Selection – IF … ELSE
●IF <expression>statement-true;
ELSEstatement-false;
Selection – IF … ELSE●Ex.
$name=”Kris”;
IF ($name=”kris”)
echo “Welcome Kris.”;
ELSE
echo “You're not Kris.”;
Selection - ELSEIF● IF <expression1>
statement-true1;
ELSEIF <expression2>
statement-true2;
ELSE
statement-false;
Selection - ELSEIF
$name=”John”;
IF ($name==”Kris”)
echo “Welcome Kris.”;
ELSEIF ($name==”John”)
echo “Welcome John.”;
Selection - SwitchSwitch (variable) {
case <value1>:statement-1;
break;
case <value2>:statement-2;
break;
default:statement-default;
break;
}
Selection - Switch$destination=”Paris”;
switch ($destination) {
case “Tokyo”:
echo “Bring extra 1000 $US”;
break;
case “Egypt”:
echo “Bring bulletproof vests”;
break;
case “Paris”:
echo “Bring a camera”;
break;
default:
echo “Dont' bring anything”;
break;
}
Loop
●While●Do While●For●Foreach
Loop - While●While (expression-true) {
statement; }
●Ex.
$i=0;
While ($i<=10) {echo $i . “<br />”;
$i++;
}
Loop – Do While
Do {
statement;
} while (expression);
Loop – Do While
$a=0;
do {
echo $a . “<br/>”;
} while ($a>0);
Loop - For●For (start; stop; increment) {
statement;
}●Ex.
For ($b=0; $b<=10; $b++) {
echo $b . “<br />”;
}
Loop – Foreach● foreach ($array as $value){
statement;
}●Ex.
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
Function● Is a block of code that can be executed
whenever we need it
● Function <name>(parameters) {
statement;
return
}
Simple functionfunction say() {
echo “Nice to meet you.”;
}
echo “Hello Kris, ”;
say();
Function with Parameters
function say($name) {
echo “<br />Nice to meet you, “. $name;
}
echo “Hello, John.”;
say(“John”);
Simple functionfunction say() {
echo “Nice to meet you.”;
}
echo “Hello Kris, ”;
say();
Function that returning values
function add($x, $y) {
$total = $x + $y;
return $total;
}
$num=0;
echo “My number is “ . $num . ”<br />”;
$num = add(5,6);
echo “Now, my number is “ . $num;
Excercise1. Write a php program to determine which one is the biggest number
from 2 numbers
2. Write a php program to determine which one is the biggest number from 3 numbers
3. Write a php program which can determine a number is odd or even
4. Write number from 1 to 20 with while, do while, and for
5. Write even number from 1 to 20 with while, do while, and for
6. Write odd number from 1 to 20 with while, do while, and for
Homework● Write a php program to determine the letter grade from given number
input (hint: use a function to generate the letter grade)
● Add a function to exercise number 1, 2, and 3