Basic PHP Syntax

Correct use of syntax is very important in programming. If the syntax is slightly wrong in HTML/CSS then your page can still look fine or may look a tiny bit odd, however in programming it will cause the application to fail (not execute). In PHP if your code is syntactically incorrect then the whole page won’t run and will print some PHP errors on your screen. Luckily the PHP error will indicate to you where the error is so you find it easily and fix it.

A PHP block must begin with <?php and end with ?>.

[php]
<?php
?>
[/php]

PHP files can contain PHP, HTML & CSS code so by using the start and end tag, the browser can identify which parts are PHP codes. PHP blocks can be placed anything in a PHP file.

A PHP file with HTML can look something the below:

[php]
<html>
<title="My Script">
<body>

<?php
echo "Hello World";
?>

</body>
</html>
[/php]

Print to screen
You can use echo or print_r() to print something to the screen inside your PHP block.
[php]
<?php
echo "Hello World";
?>
[/php]

[php]
<?php
print_r("Hello World");
?>
[/php]

echo is more commonly use for printing plain text to the screen. print_r() is generally used to print PHP Arrays.

Comments
Comments is a way for programmers to describe and explain a block or line of code within the code. It is important to comment your code so that you or others will know what a block or line of code means. PHP comments will not appear in the source code unlike HTML/CSS comments.

// is for single link comment and /* */ is for a block.

[php]

<?php
// printing hello world to the screen
echo "Hello World";

/*
printing hello world
to the screen
*/
echo "Hello World";
?>

[/php]

The Semi-colon (;)
This semi-colon is really IMPORTANT in the programming world. PHP, C, C++, C# & Java all have similar syntax and this semi-colon is one of the more important syntax.

This semi-colon tells the script when a command ends.

For example echo “Hello World” is a command because you’re telling the server/browser to print the words “Hello World” so you will end that with a semi-colon like so

[php]
echo "Hello World";
[/php]

  • This is very useful, the comments save my skin when i’m trying to understand php, thanks 🙂