PHP IF Statement: A Guide to Conditional Logic

The IF statement in PHP helps to see if a condition is true or not. If it is true, it makes the script do something different while it’s running.

    The IF statement in PHP can be written like this:

    if ( CONDITION ) {
      ... YOUR CODE HERE
    }

    So, it runs the block of code inside the two curly braces if the main condition is met. However, if the condition is not true, it skips those commands.

    In the following sections, you will see other kinds of PHP IF condition. So let’s begin with the no curly braces.

    IF Statement Without Curly Braces

    When you write an ‘if’ statement in PHP, you can ignore the two curly braces; however, PHP will only execute one line of code, which is the line following the condition, or ignore it if the result is not true. Here is the syntax:

    if ( CONDITION )  
      ... THIS LINE WILL BE EXECUTED IF CONDITION IS TRUE

    So, writing multiple lines is not permitted—only one is allowed.

    Let’s see an example:

    $is_logged_in = false;
    if ( $is_logged_in ) 
      echo "Welcome Peter !"; // this is inside the if condition
      echo "This line is not inside the condition";

    Let’s see another way for “if” condition in PHP.

    Embedding IF Statements within HTML Markup

    Imagine you’re writing a story on your website, but you want the story to change a bit if the reader is a kid. You could use an IF statement in your PHP code to do this magic trick. It’s like saying, “If the reader is a kid, show this friendly dragon picture. Otherwise, you can show another image by using else block”.

    Here’s a simple way to do it:

    $isKid = true;
    
    if ($isKid) {
        // If yes, show a friendly dragon picture
        echo '<img src="friendly-dragon.jpg" alt="A Friendly Dragon">';
    }

    You can also use the if(): and endif; constructs within HTML blocks. For example:

    <?php if ($isKid): ?>
        <img src="friendly-dragon.jpg" alt="A Friendly Dragon">
    <?php endif; ?>

    In the following section, you will learn how to write if condition inside another if condition.

    Nested IF Statement in PHP

    The concept of nesting refers to placing one IF condition or more within another IF condition. here is an example.

    if ( true ) {
         if( false ) {
           echo "Nothing will print.";
         }
     }

    Anyway, in the following section, you will learn how variables operate depending on whether the condition is true or false.

    Using Variables with IF Statements in PHP

    Sometimes, you might want to give a new value to a variable when certain conditions are met. If the condition is true, the variable gets this new value. Let’s look at an example to make it clearer.

    if ( true ) {
      $username = "Mohammed";
    }
    echo $username;

    But what happens if the condition turns out to be false? To answer this question, you need to look at the following example. As it produces an error because the variable is not defined if the PHP interpreter skips the line inside the condition.

    if ( false ) {
      $username = "Peter";
    }
    echo $username;

    This will show you the following error message.

    PHP Warning: Undefined variable $username in /workspace/Main.php on line 6

    Anyway let’s see more examples to gain a deeper understanding.

    Examples

    Here, we’ll check if a number is positive. If the condition is true, a message will be displayed.

    $number = 5;
    
    if ($number > 0) {
        echo "The number is positive.";
    }

    You can also nest if statements within each other to check multiple conditions in a more detailed manner.

    $day = "Monday";
    $weather = "Sunny";
    
    if ($day == "Monday") {
        if ($weather == "Sunny") {
            echo "It's a sunny Monday!";
        }  
    }

    Let’s summarize it in a few points.

    Wrapping Up

    The IF statement in PHP checks whether a condition is true, allowing the script to perform different actions based on this check. Here’s a concise summary of the key points discussed:

    • The IF statement evaluates a condition. If the condition is true, it executes the code block within the curly braces {}. If the condition is false, the code block is skipped.
    • For a single-line condition, PHP allows an IF statement without curly braces, executing only the immediate line following the condition if it’s true.
    • IF statements can dynamically change HTML content, such as displaying different images based on conditions. This is useful for personalizing web pages based on user data or preferences.
    • You can place IF statements within other IF statements to create complex decision trees.

    Thank you for reading. Happy Coding!

    Similar Reads

    PHP filter_id Function: How to Retrieve PHP Filter IDs

    Before PHP 5.2, there was no built-in filter extension in PHP. You had to manually handle and sanitize input. PHP…

    PHP array_map Function: How to Transform Arrays with Examples

    PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

    PHP List MongoDB Collections

    Sometimes, you may need to list collections with MongoDB in a PHP environment to manage or analyze your database structure.…

    PHP substr Function: How to Extract and Manipulate Strings

    The substr() function in PHP returns part of a string. You give it a string, a starting point, and optionally…

    How to Insert Multiple Rows in MySQL with PHP?

    Inserting multiple data rows using PHP is a basic task. However when you start working with MySQL databases, So that…

    PHP array_unshift: How to Add Values to the Start of an Array

    PHP array_unshift helps you add new elements to appear before the existing ones. Understand the array_unshift function in PHP The…

    PHP filter_var: Understand How to Sanitize Input

    PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

    PHP trim(): How to remove Whitespace from String

    Early PHP scripts often failed because of extra spaces or line breaks in strings. These issues came from user input…

    PHP MySQL WHERE: How to Filter Data in MySQL

    Filtering data is a big part of getting the right information to show up. That is where the WHERE clause…

    PHP array_push Function: How it Works with Examples

    PHP array_push lets you add one or more values to the end of an array. It appeared to make adding…

    Previous Article

    PHP Variable Scope: Local, Global & Static

    Next Article

    PHP if-elseif Statement: 'elseif' versus 'else if'

    Write a Comment

    Leave a Comment

    Your email address will not be published. Required fields are marked *


    Subscribe to Get Updates

    Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
    No spam. Unsubscribe anytime.