PHP Unit 2
PHP Unit 2
Conditional Statements
if Statement
if (condition) {
// Code to execute if condition is true
}
- **Example:**
```php
$name = "Akira";
$age = 20;
The if-else statement executes the if block of code if the condition is true,
otherwise, if the condition is false, the else block of code is executed
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
$name = "Akira";
$score = 95;
if-elseif-else Statement
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if all conditions are false
}
Example:
$name = "Akira";
$marks = 95;
Nested if Statement
if (condition1) {
if (condition2) {
// Code if both conditions are true
}
}
Example:
$name = "Akira";
$age = 20;
$registered = true;
switch Statement
The switch statement checks a variable against multiple values and executes the
corresponding block.
If a match is found, the corresponding block executes; break prevents fall-through
to the next case.
It is similar to if-elseif-else statement.
Syntax:
switch (variable) {
case value1:
// Code to execute if variable == value1
break;
case value2:
// Code to execute if variable == value2
break;
default:
// Code if no case matches
}
Example:
$name = "Akira";
$day = "Monday";
switch ($day) {
case "Monday":
echo "$name has a test today.";
break;
case "Wednesday":
echo "$name is planning to sleep.";
break;
default:
echo "$name has a regular day.";
}
Ternary operator
The ternary operator is a shorthand for if-else , returning one of two values based
on a condition.
Also known as conditional operator.
The first statement is executed if the condition is true, else the second statement is
executed.
Syntax:
Example:
$name = "Akira";
$score = 95;
$result = ($score >= 50) ? "$name passed the exam!" : "$name failed the
exam!";
echo $result;
Looping Statements
while Loop
The while loop executes code as long as the given condition remains true .
Used when the number of iterations is not predetermined.
It is an entry controlled loop, i.e. the condition is checked before executing the block.
Syntax:
while (condition) {
// Code to execute
}
Example:
$counter = 1;
do-while Loop
Similar to while , but the block executes at least once, even if the condition is
false.
It is an exit controlled loop, i.e. the condition is checked after the block of code is
executed.
Syntax:
do {
// Code to execute
} while (condition);
Example:
$attempts = 1;
do {
echo "Attempt no.$attempts.<br>";
$attempts++;
} while ($attempts <= 3);
for Loop
Example:
foreach Loop
Example:
Jumping Statements
break Statement
continue Statement
Akira (R)