What to do, if(); do, where is the semicolon immediately after the parentheses?

It happens that when I write some PHP code, I accidentally put a semicolon ; immediately after the if statement. For instance:

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

I thought that PHP should make a mistake in this case, but it is not. Such a syntax should make sense, I'm just wondering what it is.

For what I could see, the condition is always true when added ; but I'm not sure what that value is.

+6
source share
2 answers

One ; can be read as an "empty statement" and

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

equivalently

 if($a > 1) ; // execute an empty statement if $a > 1 // then execute the following block of code. { .... } 


For what I could see, the condition is always true when added ;

It only looks like the block is executed independently of the if statement.

+14
source

Adding a semicolon essentially ends the if block before curly braces. This is not true, just that you are not doing anything in if.

Think about it if you don't have braces:

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

does everything until the first semicolony inside if. So in your case, nothing happens until the first half-colony, so nothing happens.

+1
source

Source: https://habr.com/ru/post/889662/


All Articles