”;
A computer program by default follows a simple input-process-output path sequentially. This sequential flow can be altered with the decision control statements offered by all the computer programming languages including PHP.
Decision Making in a Computer Program
Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions.
You can use conditional statements in your code to make your decisions. The ability to implement conditional logic is one of the fundamental requirements of a programming language.
A Typical Decision Making Structure
Following is the general form of a typical decision making structure found in most of the programming languages −
Decision Making Statements in PHP
PHP supports the following three decision making statements −
-
if…else statement − Use this statement if you want to execute a set of code when a condition is true and another if the condition is not true.
-
elseif statement − Use this statement with the if…else statement to execute a set of code if one of the several conditions is true
-
switch statement − If you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Almost all the programming languages (including PHP) define the if-else statements. It allows for conditional execution of code fragments. The syntax for using the if-else statement in PHP is similar to that of C −
if (expr) statement1 else statement2
The expression here is a Boolean expression, evaluating to true or false
-
Any expression involving Boolean operators such as <, >, <=, >=, !=, etc. is a Boolean expression.
-
If the expression results in true, the subsequent statement â it may be a simple or a compound statement i.e., a group of statements included in pair of braces â will be executed.
-
If the expression is false, the subsequent statement is ignored, and the program flow continues from next statement onwards.
-
The use of else statement is optional. If the program logic requires another statement or a set of statements to be executed in case the expression (after the if keyword) evaluates to false.
The elseif statement is a combination of if and else. It allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Just like the else statement, the elseif statement is optional.
The switch statement is similar to a series of if statements on the same expression. We shall learn about these statements in detail in the subsequent chapters of this tutorial.
”;