Page Content

Tutorials

Conditional Statements In PHP With Example Programs

Conditional Statements In PHP

Control structures are essential components in PHP that let you manage how your program or script is executed. They give programs the ability to repeat actions and make judgements in response to particular criteria or conditions. Conditional control structures and loop control structures are the two basic categories into which control structures may be generally divided. Branching structures, another name for conditional control structures, are the subject of your inquiry.

Because they enable your program to follow many execution routes depending on decisions made at runtime, conditional control structures are essential. Depending on predetermined criteria, they either execute or bypass specific code snippets. Numerous popular conditional control structures from other programming languages are supported by PHP. The ternary operator (?:), switch statement, and if statement are PHP’s main conditional constructs.

if statement

The simplest and most widely used conditional construction is the if statement. It determines whether an expression known as the truth expression is true and, if it evaluates to true, it executes a statement or a sequence of statements. The statement or statements that follow the if are skipped if the truth expression is untrue.

Parentheses () must enclose conditions in if statements. One or more statements encased in curly braces {} can make up a block of code, often known as a statement group. Braces are always regarded as good practice, although they can be skipped if an if statement is followed by just one statement. By doing this, readability is increased and it becomes simpler to add more statements later on without making mistakes.

Here is a simple example of an if statement:

<?php
$variable = 10;
if ($variable > 5) { // The truth expression ($variable > 5) is evaluated
    print '$variable is greater than 5'; // This code is executed if true
}
// Execution continues here if the expression was false
?>

if else Statements

In many cases, you must specify a different course of action in case the condition in an if statement evaluates to false. The else statement is used to do this. Only when the expression in the if statement is false is the code block linked to the otherwise statement run.

An if else statement looks like this:

<?php
$variable = 3;
if ($variable >= 50) { // If this is true
    print '$variable is in range';
} else { // If the above is false
    print '$variable is invalid';
}
?>

if else if else Statements

The elseif construct can be used to carry out a series of conditional evaluations. Only when its own expression evaluates to true and the previous if and any previous elseif expressions were false is the elseif statement evaluated. It is possible to chain several elseif statements together. Control moves to the end of the entire if elseif else structure after executing the code block of the otherif condition if it is true. In the chain, only one block will run. If none of the previous if or elseif criteria are satisfied, the last else can act as a default case.

PHP supports both one-word and two-word elseif and else-if notations, and both styles work in the same way.

Here is an example using if elseif else Statements:

<?php
$num = -5;
if ($num < 0) { // If this is true
    print '$num is a negative integer';
} elseif ($num == 0) { // Else if this is true
    print '$num is equal to zero';
} else { // Else (if neither of the above is true)
    print '$num is a positive integer';
}
?>

To cover every scenario for a given variable or set of criteria, you can use a sequence of if elseif else statements.

Switch Statement

When comparing a single expression to a range of potential values, the switch statement is a substitute for lengthy if elseif else constructs. A root expression is evaluated, and its value is then compared to the expressions that follow case statements. The code that comes after a case expression is run when its value matches that of the root expression.

A switch statement’s execution begins at the matching case and lasts until the switch block ends or a break statement is met. After a match is located and executed, the switch is usually exited using the break statement. Execution “falls through” to the following case without interruption. An optional default statement can also be included; it is executed in the event that none of the case expressions match the root expression.

Simple types like integers, texts, or floats are ideal for switch statements. Using a switch statement instead of a lengthy if-elseif-else chain can make it easier to grasp and more convenient to compare the value of an expression against a range of possible values.

Here is a switch statement example:

<?php
$answer = 'y';
switch ($answer) { // The $answer variable is evaluated
    case 'y': // If $answer is 'y' or...
    case 'Y': // ...if $answer is 'Y'
        print "The answer was yes\n";
        break; // Exit the switch
    case 'n': // If $answer is 'n' or...
    case 'N': // ...if $answer is 'N'
        print "The answer was no\n";
        break; // Exit the switch
    default: // If none of the above cases match
        print "Error: $answer is not a valid answer\n";
        break; // Exit the switch
}
?>

The Ternary Operator ()

PHP provides a condensed form of the if else expression called the ternary operator (?:). In PHP, it is the sole ternary operator. Depending on whether the condition is true or false, the ternary operator evaluates an expression and returns one of two provided expressions. It is in the following form: (state)? If true, do this: If false, do this. Keep in mind that the actual syntax does not use the curly brackets.

The conditional operator is an operator, not a statement, and the outcome of the entire ternary expression is also an expression, which is the primary distinction from an if statement. This implies that, in contrast to if statements, it can be used inside expressions.

The ternary operator, which is really a shortcut for the if/else control structure, can provide relatively succinct code. It is seldom technically required, though, and can occasionally be difficult to read.

Here is an example demonstrating the ternary operator:

<?php
$linktext = "Click Here";
$url = "http://example.com";
// If $linktext is true (i.e., not empty or zero), use $linktext; otherwise, use $url
echo "<a href=\"$url\">";
echo $linktext ? $linktext : $url;
echo "</a>";
// This would output <a href="http://example.com">Click Here</a>
?>

The null coalescing operator (??) was included as a shortcut for basic if-isset checks in PHP 7. Although they are similar, this operator focusses on determining whether a variable is set and not null.

Alternative if Syntax

PHP offers alternative syntax for if, while, for, foreach, and switch. This alternative syntax substitutes a colon : for the opening curly brace { and endif, endwhile, endfor, endforeach, or endswitch for the closing brace }. When combining PHP code with HTML blocks, this approach can improve readability, particularly when displaying huge HTML blocks conditionally.

An example using the alternative if syntax:

<?php if ($totalqty == 0) : ?>
    You did not order anything on the previous page!
<?php else : ?>
    Here is your order summary.
<?php endif; ?>

The syntax was deprecated as of PHP 4, produces unintelligible code, and may eventually stop functioning. It is used in without any reference to deprecation. It’s important to take note of the possible issues raised in even though it does exist and can be helpful for embedding HTML.

Boolean Evaluation and Readability

The idea of true and false is the foundation of control statements. Any value entered into a control statement in PHP is transformed into a boolean. Any other string or numerical value is often regarded as true, while zero and an empty string are regarded as false.

Readability is typically a determining factor when choosing a conditional structure. Using the right construct for the job can make your code much clearer, even though there is nothing you can do using else, elseif, or switch statements that can’t be accomplished with a collection of if statements. Developers can better understand which build works best in certain situations with experience. Reading and refining complex conditional logic can be difficult. Decompose Conditional and Consolidate Duplicate Conditional Fragments simplify complex conditional phrases.

PHP’s conditional control structures if, elseif, else, switch, and the ternary operator are essential for regulating program flow under conditions. Knowing how and when to use each helps write logical, clear, and maintainable code.

Index