Categories
Past Tutorials PHP

PHP – Syntax

When writing PHP, proper syntax is paramount. If you do not write your code properly, you will receive errors, which means what your script will not work.

syntax |ˈsinˌtaks|
noun
the arrangement of words and phrases to create well-formed sentences in a language : the syntax of English.

  • a set of rules for or an analysis of this : generative syntax.
  • the branch of linguistics that deals with this.

Syntax for opening and closing a PHP document

For starters you must wrap all your PHP code within the following:

[php]

<?php

?>

[/php]

You may also use “short tags”,

[php]

<?

?>

[/php]

but I don’t recommend it, it’s better to use the standard PHP tags to insure your scripts will work on most all servers.

 

Saving your PHP code in HTML, or vise versa

Anytime you want PHP to parse your code, you must use the “.php” file extension.

[php]

<html>
<body>

<?php
echo “Hello World”;
?>

</body>
</html>

[/php]

If you were to use the “.html” or the “.htm” extension for the code above the PHP code would NOT be executed leaving you with with a markup of your php code <?php echo “Hello World” ?> instead of the output of just Hello World.

 

Escape from HTML

PHP looks for anything between the <?php ?> tags to interpret. anything outside those tags is ignored. Here’s an example of “escaping HTML” to place my PHP code:

[code]

<span>Today’s date is <?php date(“Y-m-d”); ?>. Have a nice day. </span>

[/code]

Conversley, you may also escape HTML from PHP

[code]

<?php

echo’

<html>

<body>

<p>Today is’, date(‘Y-m-d’), ‘. Have a nice day.</p>

</body>

</html>’;

?>

[/code]

 

Comments in PHP and why they are important

Comments are vital whether you’re writing a script by yourself or working on a full application with a team.

[php]

//Comments enable you to leave notes in your script.

//This is a function I want to write, I haven’t started it yet…

function liquidSwords{

}

/*

I may also have a line or block of code I can’t figure out that I want to render inert…

function Broken{

return null

}

Comments are inert in PHP, so don’t worry about it throwing errors or affecting the performance of your script.

*/

[/php]

You may comment ONE LINE by using 2 forward slashes // or an entire block of code by wrapping it between an opening /* and a closing */.

 

Semicolons

Statements in PHP should always end with semicolons.

[php]

echo ‘This is a test’;

[/php]

if you do not end your statements with a semicolon PHP will generate an error.