RelevantUsername
RelevantUsername

Reputation: 1340

Else If block and curly brackets

Knowing that in PHP we could ignore curly brackets in conditional blocks with only one function / line after the "if", "else if" or "else" tag, like this :

if (myVal == "1")
  doThis();
else if (myVal == "2")
  doThat();
else
  doNothing();

I was asking myself if something like this :

 if (myVal == "1")
  doThis();
else 
  if (myVal2 == true)
    doThat();
  else
    doNothing();

Was seen by PHP as either this :

if (myVal == "1")
{ doThis(); }
else 
{
  if (myVal2 == true)
    { doThat(); }
  else 
    { doNothing(); }
}

or this :

if (myVal == "1")
  { doThis(); }
else if(myVal2 == true)
  { doThat(); }
else 
  { doNothing(); }

Short version : Is the "line break" after one else enough to separate it from one "if" statement or will it be seen as one "else if"


Editing my own question to get a confirmation about my guess :

if(false)
  echo "1";
else 
  if (false)
    echo "2";
else
  echo "3";

Is displaying "3" while the following is throwing an error because two else statement were found :

if(false)
  echo "1";
else 
  if (false)
    echo "2";
  else
    echo "4";
else
  echo "3";

So the break line doesn't seems to make any difference, the only thing that matters is the "if" and "else" count.

Upvotes: 3

Views: 401

Answers (2)

Lukas
Lukas

Reputation: 1479

I think that both of your example results do exactly the same.

else always belongs to the preceding if unless curly braces specify it otherwise.

if (including the optional else and their subsequent statements as single-statement or curly-braces wrapped block) is always treated as a sigle statement itself, so

{
    if(...) {} else {}
}

is in fact the same as

if(...) {} else {}

Upvotes: 0

davbryn
davbryn

Reputation: 7176

Without the curly brackets PHP will treat only the next line as the block of code to execute.

if (myVal == "1")
    doThis();
else 
    if (myVal2 == true)
    doThat();
    else
    doNothing();

If myVal is "1" doThis(); is the next line and is thus picked as the block of code to execute. If there was more code there:

if (myVal == "1")
    doThis();
    doThisToo();

It would still execute only doThis() as part of the if statement, whilst doThisToo() would always be executed.

If myVal != "1" it picks the first block in the else condition and executes only that. In this case it is another if statement that needs to be evaluated:

if (myVal2 == true)

This logic continues: Identify the next block of code to execute by either taking the next line or the next block identified by a wrapping of curly braces.

Upvotes: 4

Related Questions