Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the semicolon optional in the last statement in php?

Tags:

syntax

php

I was surprised when I ran the following code in my editor:

<?php      echo "hello";     echo "world"  ?> 

As it can be easily seen, a semicolon (;) is missing from the code, however it still works!

How this works and why ; is {0,1} here?

like image 681
user4679529 Avatar asked Mar 26 '15 16:03

user4679529


People also ask

Is semicolon optional in PHP?

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block.

What is the correct way to end a PHP statement?

Note: PHP statements end with a semicolon ( ; ).

Why is colon used in PHP?

In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator.

How do you end a file in PHP?

In PHP, statements are terminated by a semicolon (;) like C or Perl. The closing tag of a block of PHP code automatically implies a semicolon, there is no need to have a semicolon terminating the last line of a PHP block.


1 Answers

Because the close tag implies a semicolon. You can read more about this in the manual under Instruction separation.

And a quote from there:

As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement. The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block. The closing tag for the block will include the immediately trailing newline if one is present.

An example to prove this:

1. script with missing semicolon at the end, but with closing tag:

<?php     echo "1";     echo "2"           //^ semicolon missing ?> 

output:

12 

2. script with missing semicolon at the end, but without closing tag:

<?php     echo "1";     echo "2"           //^ semicolon missing (closing tag missing) 

output:

Parse error: syntax error, unexpected end of file, expecting ',' or ';' in

like image 133
Rizier123 Avatar answered Sep 21 '22 07:09

Rizier123