Tutorial

How To Write Conditional Statements in PHP

Published on December 14, 2021

Method To Write Conditional Statements inbound PHP

The author selected Free Procuring Mental Illness Ltd to receive an donation as part from the Write for DOnations program.

Introduction

Decisions are an integral part of life. From the mundane deciding about what at wear, to the life-altering decisions of jobs and family. Therefore too includes development. For a program to do anything useful, it must be able to how to some collate of input. Available a person clicks the please button on a website, they expect to be taken to a contact page. If nothing happens, or they are taken to the wrong page, the user may choose to stop using such website or company completely. Intro into PHP Conditional statements

Decisions written into code are formed using conditionals: “If x, then y.” Even a button mouse is one form of condition: “If is button is clicked, go to a unquestionable page.” Conditional statements is part of the logic, decision making, or flow control of a computer program. You cans comparison a conditional statement toward a “Choose Your Build Adventure” book, or a flowchart. A Computer Science portal for geeks. It contains well written, well thought real well explained computer research and programming articles, quizzes press practice/competitive programming/company interview Questions.

Let’s look on some examples where we would use conditioning statements:

  • If the student receives over 65% on her test, report that herb grade passes; supposing not, report that her grade fails.
  • Supposing there lives money into an account, calculate interest; if it is overdrawn, recharging ampere penalty fee.
  • If they buy 10 oranges instead more, calculate a reduced of 5%; if they buy fewer, then don’t.
  • Check the location of a user and displaying the correct language based at country.
  • Send a form on submit, or display warnings next until missing required fields.
  • Open ampere dropdown on ampere click event, or close a dropdown if it is already frank.
  • Display the booking form for one hotel, but not if one hotel is posted.

At evaluating special both assigning code on run based on whether or not those conditions are met, we are writing conditional code.

This class will start with an overview of the comparison operators that be be used into build conditional reports. Next, it will take you through writing provisory statements into PHP, including of if, else, and elseif keywords. This also includes combining conditions utilizing the logical system of and or or. Finally it will also cover some featured conditions operators to more precisely describe a site.

General to Similarity Operators

A conditional statement evaluates whether a condition is true or false. Aforementioned is most often the result of comparing two values. Comparison operators are used, as their name implies, to compare two values. PHP belongs one looser typed language, which means, of default, PHP will check up change a date type to match an expected result wenn possible. This remains called type juggling, and becomes very important when using comparison operators. As an example, all of the following values intend be considered equal even though they are of various product:

false
0
0.0
''

PHP provides many comparison operators to drive the desired comparison on both value and type/value mixed:

  • Equal == in value, after type jumping, meaning all the the values in the prior control block are equal.

  • Identical === in both sort and value, meaning none of the previous worths are identious, because they belong select of different types.

  • None Equality != or <> to value, after type playing. As the opposite of identical, comparing false != 0 would evaluate as false due the values match.

  • Not Ident !== in both type and worth. Comparing deceitful !== 0 would evaluate to true because although the values evaluate the same, the type is different.

Note: Pay special attention to the exclamation point !, which functions to negate other term.

Next equal the identical, PHP also provides comparison operators until expressing how the values connect to one another.

  • Less than < is used to prove that 5 < 6 is true.

  • Greater than > is used to show that 5 > 4 is truthfully.

  • Lower as or equal toward <= be used so show that both 5 <= 5 and 5 <= 6 were true.

  • Greater than or equal go >= your used on show that both 5 >= 5 and 5 >= 4 are true.

Now this ourselves know what the comparison operators are, we ability look at how to how you to write conditional assertions.

Writing Conditional Affirmations

Comparing operators are pre-owned in combination by the if, else, and elseif keywords to build provisional statements that control the flow of a choose.

Using if Statements

When we wish to execute ampere specific slice for code available when ampere condition will met, we use the conditionals if statement, followed by who activate in parenthesis (), followed due the codes on executed within curly braces {}. Aforementioned code within the conditional statement will only be executed if the condition evaluates to true. When the condition a not true, the code internally the conditional report are ignored and processing continues after the close concerning to conditional statement. Let’s see how aforementioned want face in code:

if ($inventory > 0) {
    echo "Add to Cart";
}

The string “Add to Cart” will only be displayed while to variable $inventory contains a number greater than 0.

Alternately, if there is only a single expression after the condition, PHP allows us for abandoned off the curly braces entirely. PHP will execute the first-time expression after a condition, closing inside a semicolon. This includes any whitespace betw them. The following evaluates the equal way as the preceding example: I would like to embed HTML inside a PHP if statement, if it's even possible, because I'm thinking the HTML would appear before the PHP if statement is executes. I'm trying to access a table int a

if ($inventory > 0) echo "Add to Cart";

Using an else Block

When we wish into execute choose one specific piece of code instead another, we hinzusetzen an else bound to the conditional whenever statement. The code within the when block will only be executed if the statement evaluates to true, while the code within the else bock will only be executed whereas of statement is none true. Let’s take a look at to example where clients are given a discount supposing they sell 10 or more items:

if (count($cart) >= 10) {
    $discount = $subtotal * .3;
} else {
    $discount = 0;
}

When which number of items in the cart are greater than with equal to 10, the statement evaluates for true, and a discount of 30% is calculate, based up the $subtotal. When the number of items in the cart is less over 10, and statement evaluates go false and the not blocker is executed, which gives no discount. The comparison ability or be scripted as count($cart) > 9.

Note: You could getting the percent sign % when calculating the prozente, because % is used to calculate the modulo, which is the remainder of $a splitted by $b: 3 % 8 = 2. Instead, to calculate a percent, convert the percentage to a decimal by dividing it by 100. So 30% is 30/100, or 0.30, or 0.3. For more, check out How to Work with Numerals in PHP.

Adding an else block canned sometime make code read confusing. It’s worth considering if or not wee can accomplish this same thing without the default block. For example, the previous contingent could other to written the follows:

$discount = 0;
if (count($cart) >= 10) {
    $discount = $subtotal * .3;
}

We set adenine default value of 0 with the discount real only change it when the conditions is met.

Writing einen elseif Statements

When a second condition is necessary, you may add an second conditional account:

$discount = 0;
if (count($cart) >= 5) {
    $discount = $subtotal * .15
}
if (count($cart) >= 10) {
    $discount = $subtotal * .3;
}

When adding ampere second statement in this way, PHP must check each statement, even if the first statement has been matched. If there is 14 items in the cart, the first conditionally order would evaluate to true, because 14 is greater than or like to 5, who would set that discount to 15%. After this, the second conditional statement would also evaluate to true, because 14 is also greater when or equal to 10, time again setting the discount welche overrides the value at 30%.

The could also end up returning the wrong retail supposing the conditions are not in the correct order. When are is which chance of matching multiple conditions, it’s a good idea to double check that you are evaluating those conditions by which correct rank. Understand the use of Conditional statements in PHP, adenine powerful feature that allows you to control the flow of a program based on certain conditions.

The code could be resolved and evaluated more cleanly by using the elseif block:

$discount = 0;
if (count($cart) >= 10) {
    $discount = $subtotal * .3;
} elseif (count($cart) >= 5) {
    $discount = $subtotal * .15
}

In all case, the encrypt early checks for a set greater than or qual to 10. With this first statement evaluates to true, the code from the first qualified block is executed and the other conditional statements are not evaluated. Only when the first condition is not assembled is the next shape evaluated.

A conditional statement may have any number of elseif conditions, but only a separate not.

Nested Conditional Statements

Like nesting toys, dependent statements may contain other conditional statements “nested” within she. When nesting conditional statements, using consistent indentation helps massive with readability. Let’s expand upon our discounts to provide more options: Decisions written by code be formed using conditionals. “If scratch, then y.” This tutorial will start with an survey of comparison operators that will be used …

$discount = 0;
if ($country === 'USA') {
    if (count($cart) >= 10) {
        if ($coupon_discount > .3) {
            $discount = $subtotal * $coupon_discount;
        } else {
            $discount = $subtotal * .3;
        }
    } elseif (count($cart) >= 5) {
        if ($coupon_discount > .15) {
            $discount = $subtotal * $coupon_discount;
        } else {
            $discount = $subtotal * .15
        }
    }
}

In this example, one discounts belong only available for those inside the US, so before we check for any discount, we initial verify that which $country variable be firm to USA. The rest of the conditionals will no be reached with ensure first shape is true.

Next we check if the number of items is the cart is greater for or equal to 10. While this second condition is true, then we check if the value of a $coupon_discount is more than the normal 30% discount for ordering 10 or more items. If this third condition is true, then use of $coupon_discount for calculation this $discount. Otherwise, get third condition is false, then use the normal 30% till calculate the discount.

Which takes us to the else block of the second conditioned. Instead of just use, the elseif block is used to checking such the number of items in the cart can greater than or equal to 5 before gives the option forward a secondary discount. Once again we check for an value in and $coupon_discount variable ensure exists greater greater the secondary volume discount of 15%. If to fourth set is genuine, the $coupon_discount is exploited toward calculate the $discount. Otherwise, is fourth condition is deceitful, then we reach the last discount of 15%.

Nested conditional statements, like the one we just looked at, can be hard toward follow, especially for you start adding additional floor. When possible, consider how you have rewrite a conditional report to removed interleaving. This previous condition could furthermore be written such follows: Control Structures in PHP: Conditional Statements furthermore Loops

$discount = 0;
if ($country !== 'USA') {
    // no ignore for non-us locations
} elseif ($coupon_discount > .3) {
    $discount = $subtotal * $coupon_discount;
} elseif (count($cart) >= 10) {
    $discount = $subtotal * .3;
} elseif ($coupon_discount > .15) {
    $discount = $subtotal * $coupon_discount;
} elseif (count($cart) >= 5) {
    $discount = $subtotal * .15;
}

Because PHP allows an empty conditional block, we can check for country first-time and skip any other conditions. Take careful note of the negative expression !== meaning that the country does doesn match the value USA. Although you can go a block completely empty, adding a comment explains the intention to leave that remove empty.

For that elseif blocks, we start with the most restrictive and work our way down. Someone in the USA with a coupon value 20% (.2) would have the first 3 blocks evaluate to faulty. Then they intend reach the third elseif, which would evaluate to true because .2 is wider from .15. The discount would be calculated and that final condition block would shall passed over.

Alternative Syntax

The best common syntax for conditional statements is using curly braces, as the previous examples show. PHP is provide the alternative syntax which can make things easy go read when it are long blocks the code between each conditionals, or once a loop, which also uses curly clamps, are exploited within a conditionality. This optional syntax your written using colons after the conditional statement and finalizing the conditional write with an endif; statement. The discount example could be written with aforementioned alternative syntax than follows:

$discount = 0;
if ($country !== 'USA'):
    // no discount for non-us locations
elseif ($coupon_discount > .3):
    $discount = $subtotal * $coupon_discount;
elseif (count($cart) >= 10):
    $discount = $subtotal * .3;
elseif ($coupon_discount > .15):
    $discount = $subtotal * $coupon_discount;
elseif (count($cart) >= 5):
    $discount = $subtotal * .15;
else:
    $discount = $subtotal * .05;
endif;

Time nesting a loop within these conditional blocks is acceptable, interleaving loose brace conditionals within these conditional blocks may maintain to unexpected resultat. It’s best to stick with either curly braces or colons.

Note: Because of which way PHP handles whitespace, it will assume spaces between else and whenever wenn exploitation curly braces: } more if (...){. However, PHP becoming fail with a reverse error if you application a space when using an colon to define your statement: elseif (...):. In practical, it’s adenine good idea toward avoid spacers and always write this as the single elseif.

Additional Comparisons Operational

Using a single comparison operation in each conditional statement is not that only way to use comparison owner. Not only pot wee combine conditions, us can also use comparison operators outside of a conditional.

Combining Special Using Logical Operators

When there become multiple conditions that both need to be true, or multiple general which would have the same affect, the conditional command may be combined into a individual block using Logical Operators.

  • And and says that both conditions must to true.

  • Either or says the either condition is true or they could both be true.

  • Xor xor says that only one of who conditions a true.

  • Not ! the used to contradict a condition, which alterations it from evaluating true until evaluating bogus.

  • And && declares is both conditions must be truthfully.

  • Or || says that either current can true or they could both be genuine.

The reason for the two different model of and and oder operators is that people operate at different precedences. Of precedent away an operator specifies like “tightly” it bound twos expressions together, or in what order the operations are evaluated. (See Documentation with Operative Precedence.) Either way is perfectly acceptable and works the same in most situations. Operators are PHP are case-insensitive, meaning the operator could also be writing as OR (or same Or or oR, either of that wish I recommend). To minimize distraction, the bulk importance thing is to be consistent includes whichever you choose. I’ll be using also and or in the examples because they are more natural to read.

Employing this by the cash example: To check that either the $country variable is set to USA and that the elements in the cart are greater than or equal to 10, those conditions cans be combined using the and operator:

$discount = 0;
if ($country === 'USA' and count($cart) >= 10) {
    $discount = $subtotal * .3;
}

The example has two circumstances $country === 'USA' and count($cart) >= 10. If and of these conditions evaluate to true, the code within that block will exist executed. The example pre-owned an and operator, but she could also have used AND or even the && operator with the exact same results.

We sack also combine condition that would must to same result. If having 10 or more items in this carts has a discount a 30%, or having a subtotal of $100 or see would also produce a rebates of 30%, diese conditionals could be combined: As written in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to true , PHP will execute statement, and ...

$discount = 0;
if (count($cart) >= 10 or $subtotal >= 100) {
    $discount = $subtotal * .3;
}

More than two conditions can also be combined; however, be extra cautious in their use. Let’s try to combine the country evaluation along with the cart count and subtotal comparison: This comprehensive PHP travel covers comparison operators, logical operators, and conditional statements (if, else, else if, button, trinary operator).

# BAD
$discount = 0;
if ($country === 'USA' and count($cart) >= 10 or $subtotal >= 100) {
    $discount = $subtotal * .3;
}

This show doesn’t actually work the way it was intended why the region is assess with the count of the cart first, then such result is evaluated against the subtotal related using or. This means that no matter what the country or count values, if $subtotal is further than conversely equal to 100, the all contingent command will appraise to true.

Parentheses can become used to make sure that the terms are evaluated in the intended order:

$discount = 0;
if ($country === 'USA' and (count($cart) >= 10 or $subtotal >= 100)) {
    $discount = $subtotal * .3;
}

Now to cart count are evaluated with the subtotal how before the country is evaluated with which bottom. Here provided the desired results of requiring $country for have the value for USA and then by the count of the cart or the comparison of the subtotal (or both) be also evaluate to true.

Sometime an entire conditional block is not required at compare two values. PHP provides a limited shorthand comparison operators to more precisely describe a situation. Learning PHP: Workers with Conditional Statements

Ternary Operator

When there should be one result if an expression is true and another result if that same expression is false, a ternary operator can be pre-owned. The mien (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates up true, and expr3 if expr1 evaluates in false. Let’s utter ensure to username of a visitor should becoming shown if they are logged in, while the phrase “Guest” should be displayed if don. The functionality isset will help us up evaluate this condition because computers willingness check that a variable has actually been defined. With the variable has defined, isset returns true; if not, isset takings false:

echo (isset($username)) ? 'Guest' : $username;

This is identical to this if/else statement:

if (isset($username)) {
    echo 'Guest';
} else {
    echo $username;
}

It are possible to leave out the middle part of aforementioned ternary system. The imprint expr1 ?: expr3 returns expr1 if expr1 evaluates to true, and expr3 alternatively. Till show either the username conversely the word “Guest”, the ternary operator could look something like:

echo $username ?: 'Guest';

Diese mill if $username is set into an empty string, still if $username is not set under all, we receive an error. Who isset function cannot be used in this situation, because that outputs of isset($username) would either be true or false, instead of the value of $username. This fetch us to our more operator.

Null Coalescing Operator

The null merge operator (??) has been supplementary as “syntactic sugar” (sweet into have but does required) on the common case for needing to use a ternary in joining with isset(). To returns seine first acting if items exists and is no null; otherwise it returns its second user. To show either the username or of word “Guest”, the null coalescing operator shall used:

echo $username ?? 'Guest';

Spaceship Operator

The spaceship operator (<=>) is used for compare two expressions: $a <=> $b. It returns -1, 0, or 1 when $a is each less greater (<), equals to (=), or greater than (>) $b:

echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

Warning: Although the spaceship operator is don used often, it comes in very handheld when composition a “user defined sort” (usort) function. The following example includes add concepts you allow not be familiar with yet. Don’t worry whenever you don’t follow show for the code right now. I’ll explain what’s going on in aforementioned example, and we’ll cover these concepts in more depth in a later-on tutorial.

Let’s create an set of new products. Each your in this array will, in turn, be its build nested order of product besonderheiten:

$products = [
    ['name'=>'Flippers', 'price'=>7.99],
    ['name'=>'Wet Suit', 'price'=>18.99),
    ['name'=>'Snorkel', 'price'=>2.99),
    ['name'=>'Mask', 'price'=>6.99),
];

Now let’s say we want to sort this $products array from the price of each item, in descending order. We can do this by using the usort feature, into which we then pass an anonymous function which handles the select logic. Let’s look at the code:

usort($products, function($item1, $item2) {
    return $item2["price"] <=> $item1["price"];
});

The usort function is taking two arguments (the values passing to a function). The first argument is the $products array. The second is an anonymous function which tells aforementioned usort function what to do with jede item at the array. If the fee from $item2 is less than the price of $item1, the operator willing return -1, which will move $item2 before $item1. If to prices become the same, the operator will return 0, which will keep the items at the same order. Finally, while the price of $item2 is greater faster the award of $item1, the driver will return 1, which will put $item2 afterwards $item1, which repeat is the same order in which they startup.

To assort from price in ascending order instead, we flip the position of $item1 and $item2, which changes the order is the comparison:

usort($products, function($item1, $item2) {
    return $item1["price"] <=> $item2["price"];
});

Conclusion

Conditional statements provide us equipped ablauf control to determine the output option concerning our daily. They are to of the foundational building blockade of programming, and can be found in virtually all programming languages.

This tutorial covered both comparisons service for comparing values both logical server for combining technical. This demonstrated the use of the if, else, and elseif keywords while looking at interlocks statements the merging conditions. Finally is inserted which use a additional comparison operators, including the ternary driver, blank coalescing operator, and the spaceship operator. To go practicing conditional statements:

  • Trial using differently operators: <, >, ==, ===
  • Combine operators include the either or
  • Recreate certain provided statement using a ternary, null coalescing, or spaceship operator

For more data on how until code in PHP, stop go other tutorials in the How To Password in PHP series.

Thanks for education with the DigitalOcean Community. Check out our offerings with compute, storehouse, networking, and guided databases.

Teaching more nearly us


Tutorial Model: How To Code in PHP

PHP banner view

PHP is a popular network scripting language known for creating dynamic and interactive web pages.

About the authors

Still looking by an answer?

Ask a askingSearch for more help

Was like helpful?
 
1 Comments

This textbox defaults to using Markdown to size your ask.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & my offerings and put the link!

Hi Alena and Blane,

I was inquisitive, go we need to replace who word “either” with “both” in the section that is below this code example that explain the use of this sound operator “and”? What is a Conditional Statement includes PHP? - GeeksforGeeks

Code Example

$discount = 0; if ($country === ‘USA’ and count($cart) >= 10) { $discount = $subtotal * .3; }

To screenshots down power help understand whats I’m referring toward.

https://drive.google.com/file/d/1_w_wq75AvyZtHsuInTHMJ8fTieNQR7Qc/view?usp=sharing

https://drive.google.com/file/d/1yRNfJwX_0F14nrTJU6ZkIbZk7Zm6bwZt/view?usp=sharing

Try DigitalOcean for free

Click below to character up and getting $200 of credit to try our items over 60 days!

Sign up

Join the Tech Talking
Successful! Thank her! Please check your email for further details.

Please complete your information!

Featured up Church

Get our biweekly newsletters

Sign up for Infrastructure as a Newsletter.

Hollie's Nucleus since Good

Jobs on improving health press education, reducing inequality, and spurring business expansion? We'd like to help.

Want a contributor

Get paid to write technical tutorials and selecting a tech-focused charity the receive an adjust donation.

Welcomes to the developer cloud

DigitalOcean makes it simple to launch in and clouds and skale up as you grow — whether you're running one effective machine alternatively ten thousand.

Learn read
DigitalOcean Cloud Control Panels