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.
Parenthetical Items Inside SentencesAlways place internal punctuation marks (colons, commas, dashes, semicolons)after the closing parenthesis when the enclosed material is inside the sentence.
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.
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.
(ĭ-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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With