else

(PHP 4, PHP 5, PHP 7, PHP 8)

Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what else is for. else extends an if statement to execute a statement in case the expression in the if statement evaluates to false. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise:

<?php
if ($a $b) {
  echo 
"a is greater than b";
} else {
  echo 
"a is NOT greater than b";
}
?>
The else statement is only executed if the if expression evaluated to false, and if there were any elseif expressions - only if they evaluated to false as well (see elseif).

Note: Dangling else

In case of nested if-else statements, an else is always associated with the nearest if.

<?php
$a 
false;
$b true;
if (
$a)
    if (
$b)
        echo 
"b";
else
    echo 
"c";
?>
Despite the indentation (which does not matter for PHP), the else is associated with the if ($b), so the example does not produce any output. While relying on this behavior is valid, it is recommended to avoid it by using curly braces to resolve potential ambiguities.

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe
There are no comments available yet.

Midjourney Tutorial - Instructions for beginners

There is an informative video about Midjourney, the tool for creating digital images using artificial intelligence, entitled "Midjourney tutorial in German - instructions for beginners" ...

Mike94

Autor : Mike94
Category: KI Tutorials

Basics of views in MySQL

Views in a MySQL database offer the option of creating a virtual table based on the result of an SQL query. This virtual table can be queried like a normal table without changing the underlying data. ...

admin

Autor : admin
Category: mySQL-Tutorials

Definition of stored procedures - an introduction

Stored procedures are predefined SQL code blocks that are stored in a database and can be called up as required. ...

Bernie

Autor : ebiz-consult GmbH & Co. KG
Category: mySQL-Tutorials

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial