The PHP else block can be used if the condition failed to achieve the the true result and that leads the current process to execute the other block in else statement.

IF Else in PHP

Let’s see the basic syntax.

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

So, if the main IF condition has a false result, it will execute the bottom block in else { ... }.

We can write else { .. } block with curly braces, without curly braces, or with embedded. Let’s see that.

The IF Else with Curly Braces

It is the same previous syntax else word and beside it curly braces { ... }. Let’s see an example.

<?php
  $is_logged = false;
  if ( $is_logged ) {
  
  } else {
    echo "Invlaild Username or Password!";
  }
?>

Also, you can use the PHP if else with no curly braces. Let’s move to the following section to see that.

PHP IF Else with No Curly Braces

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

<?php
  $is_logged = false;
  if ( $is_logged ) 
    echo "Welcome to home page";
  else 
    echo "Invalid Username or Password";
?>

Also, you can use it with any language else such as JavaScript, HTML, and so many others.

PHP IF Else with Embedded Syntax

Here you can use PHP code with HTML markups or any others, so if the condition not achieved it will print another thing. Let’s see that.

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

The JavaScript code would be executed inside the else expression.

Wrapping Up

The if else is used to execute PHP statements when the if condition is failed to reach to the true boolean value.

Additionally, the if else can be written with curly braces, with no braces, or with embedded syntax and here you can use it with any language else.