Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does if(); do, where the semi-colon is right after the parentheses?

It happens that, when writing some PHP code, I accidentally put a semicolon ; right after an if statement. For example:

if($a > 1);
{
   ....
}

I thought that PHP should raise an error in this case, but it is not. That kind of syntax should have a meaning, I'm just wondering what it is.

For what I could see the condition seems to be always true when the ; is added but I'm not sure at all this is the meaning.

like image 415
Dalen Avatar asked Jun 02 '11 21:06

Dalen


People also ask

Can you use a semicolon after a parentheses?

Parenthetical Items Inside SentencesAlways place internal punctuation marks (colons, commas, dashes, semicolons)after the closing parenthesis when the enclosed material is inside the sentence.

What happens if you put a semicolon after an if statement?

Do not use a semicolon on the same line as an if , for , or while statement because it typically indicates programmer error and can result in unexpected behavior.

What happens if you put a semicolon after an if statement Java?

The semi-colon in the if indicates the termination of the if condition as in java ; is treated as the end of a statement, so the statement after if gets executed.

What Does a colon with a parentheses mean?

(ĭ-mō′tĭ-kŏn′) n. A facial glyph, used especially in email, texts, and instant messages and sometimes typed sideways, that indicates an emotion or attitude, as [ :-) ] to indicate delight, humor, or irony or [ :'( ] to indicate sadness.


2 Answers

A single ; can be read as an "empty statement" and

if($a > 1);
{
   ....
}

is equivalent to

if($a > 1)
    ;        // execute an empty statement if $a > 1

// then execute the following block of code.
{
   ....
}


For what I could see the condition seems to be always true when the ; is added

It only seems like it since the block is executed regardless of the if-statement.

like image 134
aioobe Avatar answered Oct 20 '22 00:10

aioobe


Adding the semi-colon essentially ends the if block before the braces. It isn't true, it's just that you don't do anything in the if.

Think about it like this, if you don't have braces:

if($a>1)
  echo "Yes";
echo "No";

does everything before the first semi-colon inside the if. So in your case, there is nothing before the first semi-colon, so nothing happens.

like image 41
awestover89 Avatar answered Oct 20 '22 00:10

awestover89