Learning the PHP Syntax

php-syntaxThis tutorial will introduce you with the basic PHP syntax. After going through this tutorial, you will be familiarized with basic PHP syntax, PHP functions and PHP variables and you able to write a basic script in PHP.

PHP Syntax and Semantics:

The PHP Syntax ( Format ) and Semantics (Meaning) combines to form a set of rules using which, a coder can write scripts in the PHP language and interpret them.

In short, PHP syntax must be followed in order to write error free programs and get correctly executed outputs.

Overview:

  • A PHP script always starts with <?php and ends with ?>
  • PHP processor only parses the code which is inside its delimiters (<?php and ?>). Anything outside these delimiters are not parsed by the PHP processor.
  • Servers that have support for shorthand also treat <? And ?> as delimiters.
  • The end of each PHP statement is marked with a semicolon (;)
  • Variables, in PHP language,  are prefixed with a dollar ($) sign and does not need a data type for initialization.
  • Block comments can be made by using /* and */
  •  Inline comments can be made using // or #

A Basic PHP Script:
Here is a basic PHP script

  • The PHP code is embedded between HTML (<html> and </html>
  •  The PHP code is encoded between the delimiters <?php and ?>
  • Each PHP statement is ended by a semicolon (;)
  • The PHP markup display text on the screen by using “echo”

 

<html>
<body>

<?php
echo “Hello World”;
?>

</body>
</html>

 

Output:

Hello World

PHP Variables:

Here is a simple PHP script containing PHP variables:

  • Variables, in PHP language,  are prefixed with a dollar ($) sign and does not need a data type for initialization.
  • Variables have local and global scope
  • A function will not recognize a variable that has been declared outside its scope.
<?php
$var1 = 'hello';
echo $var1;
>?

Output: Hello

PHP Functions:

Here is a simple PHP function:

  • The PHP code is encoded between the delimiters <?php and ?>
  • Each PHP statement is ended by a semicolon (;)
  • The function is defined before it is called in the code

<?php

function Test()

{

echo “Hello World!n“;

}

 

Test();

?>

Ouput:  Hello World

 

Leave a Reply