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 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…

    Static Method in PHP: How They Work in Classes

    PHP static method lets you call functions without an object. In this article, we will cover the following topics: The…

    PHP $_POST: Handling Form Data in PHP

    The term $_POST is quite familiar territory when one works with forms in PHP. This tutorial talks about what $_POST does, how to use…

    PHP Comparison Operators Guide with Examples

    PHP comparison operators allow you to compare values in many ways, and this simplifies the process of checking whether values…

    PHP Comment: How to Write Comments in PHP

    let's now dive into PHP comments—these simple but super important integral parts of PHP coding. You can think of comments…

    PHP $GLOBALS: Access Global Variables with Examples

    When you start working with PHP, you’ll soon need access to variables from multiple places in your code. For this,…

    IF-Else: Executes the IF-Else Statement in PHP

    Programming is all about choices. Everything you do in code boils down to answering a question: What should happen if…

    Master PHP Iterables: Arrays, Objects, Traversable Interface

    The first appearance of PHP iterable was in PHP version ( 7.1 ) – Iterables are a powerful feature in…

    PHP Switch | How the Switch Statement Works in PHP

    The PHP switch statement is multiple conditions to only execute one block if its condition generating a true boolean value.…

    How to Update MySQL Data with PHP?

    Understanding how to update data in PHP and MySQL is like editing a draft—it is all about tweaking the right…

    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.