Technology

New Syntax for If Statements

Explore the new if statement syntax for simplified coding. This guide introduces a cleaner, more efficient way to write conditional statements in programming.

Sangrak

I have always coded if statements like this:

if ($a == "a") echo "test";
else echo "test2";

Or like this:

if ($a == "a")
{
    echo "test";
}
else
{
    echo "test2";
}

However, recently I was looking for a way to write multiple commands in one line without using curly braces {} and discovered this new syntax.

if ($a == "a"):
    echo "test";
    exit;
else:
    echo "test2";
    echo "test3";
endif;
 echo "EOF";

This allows for a simple if statement to be written without {}, using : and endif; instead.

The new syntax can be conveniently used like this:

if ($a == "a")
{
    echo "test";
    myfunc($a);
    exit;
}

Can be simplified to:

if ($a == "a"): echo "test"; myfunc($a); exit; endif;

This provides a more streamlined and efficient way to code conditional statements.

More on this topic