We use the PHP if-else block if the condition fails to achieve the true result, leading the current process to execute the other block in the else statement.

IF Else in PHP

Here is the basic pattern for the else block in the if condition:

if ( false ) {
} else {
    // => YOUR CODE HERE

If the main IF condition yields a false result, it will execute the block within the else { ... }.

Additionally, we can write the else block without curly braces or with embedded code; let’s see how we can do that.

Else with No Curly Braces

In this syntax, you will be able to write only one statement. Thus, many statements will not be allowed without curly braces.

Let’s see an example:

$is_logged = false;
if ( $is_logged ) 
  echo "Welcome to home page";
  echo "Invalid Username or Password";

Also, you can use it with any other language, such as JavaScript, HTML, and many others. Let’s see how that is done in the section below.

PHP IF Else with Embedded Syntax

Here, you can use PHP code with HTML markup or any other. If the condition fails, it prints something else. Here’s an example:

<!DOCTYPE html>
    <title>The PHP IF ELSE</title>
    <?php if ( false ): ?>
    <?php else: ?>
       <script type="javascript">alert("Hello World");</script>
    <?php endif;?>
     <h1>Welcome to Home Page !</h1>

In this example, the JavaScript code is executed once the main if statement fails to meet the condition.

Let’s summarize it.

Wrapping Up

The if-else statement is used to execute PHP statements when the if condition fails to evaluate to the true boolean value.

Here is a quick example:

if ( false ) {
} else {
  // This block executes once the if condition fails to execute.

Additionally, the if-else statement can be written with curly braces, without braces, or with embedded syntax, and here you can use it with any other language as well.

Thank you for reading. Happy Coding!