Control Statements


Control statements are conditional statements that execute a block of statements if the condition is true. The conditional block's statement will not be executed until the condition is met.

Types

"If" is a conditional statement.

The? operator is used to ask questions.

The switch statement is a conditional statement.

Exceptions Declare loops that exit, die, and return.

If is a conditional statement.

if(expression1) { Only executes when the ic condition is correct. } elseif(expression2) { Executed when the if expression1 is false and the expression 2 is true. } else { Executed only when the both if blocks are false. }

If the expression inside the parentheses evaluates to true, the if statement executes the statement; otherwise, the code is skipped to the next block. It can be either a single statement followed by a semicolon or a compound statement enclosed in curly braces. Another statement might occur right after the statement and have its statement. It is only executed if the previous expression is false; otherwise, it is ignored.

A simple if condition:

<?php $a=10; $b=5; if ($a > $b){ echo "a is greater than b"; } ?>

output:

a is greater than b

? operator

It is a conditional operator that is expressed as a ternary operator, and it is primarily assessed as either false or truthful. If false, the expression adjacent to the ternary operator is run, else the expression between the ternary operator and the colon is run.
Expression of a condition? false: true;
It is mainly used to decrease code size, but it may also reduce complexity.

? operator

<?php $a = 15; $b = $a > 20 ? 25 : 10; print ("Value of b is " . $b); ?>

output:

Value of b is 10

Switch Operators

The condition is tested with each expression inside the switch, with numerous expressions. In the switch statement, there is a default statement that may be used in the else statement; both have the same functionality and operate in the same way. A case is the first step in the execution process.

<?php $favcolor = "blue"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!"; } ?>

output:

Your favorite color is blue!

The break is also a control statement used to halt the execution of the statement after it. It can compare two strings and perform the appropriate statement in the switch.
When a case statement is used to satisfy a condition, the remaining case statements are skipped unless the break statement is used, in which case the switch statement executes all of the case statements.