Sunday, June 1, 2014

PHP Tutorials -> Syntax and Variables

PHP Syntax

Basic PHP Syntax

A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document.
On servers with shorthand support enabled you can start a scripting block with <? and end with ?>.
However, for maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form.
<?php
?>
A PHP file normally contains HTML tags, just like an HTML file, and some PHP scripting code.
Below, we have an example of a simple PHP script which sends the text "Hello World" to the browser:
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print. In the example above we have used the echo statement to output the text "Hello World".

Comments in PHP

In PHP, we use // to make a single-line comment or /* and */ to make a large comment block.
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>



PHP Variables

Variables in PHP

All variables in PHP start with a $ sign symbol. Variables may contain strings, numbers, or arrays.
Below, the PHP script assigns the string "Hello World" to a variable called $txt:
<html>
<body>
<?php
$txt="Hello World";
echo $txt;
?>
</body>
</html>
To concatenate two or more variables together, use the dot (.) operator:
<html>
<body>
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2 ;
?>
</body>
</html>
The output of the script above will be: "Hello World 1234".

Variable Naming Rules

  • A variable name must start with a letter or an underscore "_"
  • A variable name can only contain alpha-numeric characters and underscores (a-Z, 0-9, and _ )
  • A variable name should not contain spaces. If a variable name should be more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString)

0 comments:

Post a Comment