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.
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:
You may also use “short tags”,
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.
echo “Hello World”;
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:
<span>Today’s date is <?php date(“Y-m-d”); ?>. Have a nice day. </span>
Conversley, you may also escape HTML from PHP
<p>Today is’, date(‘Y-m-d’), ‘. Have a nice day.</p>
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.
//Comments enable you to leave notes in your script.
//This is a function I want to write, I haven’t started it yet…
I may also have a line or block of code I can’t figure out that I want to render inert…
Comments are inert in PHP, so don’t worry about it throwing errors or affecting the performance of your script.
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 */.
Statements in PHP should always end with semicolons.
echo ‘This is a test’;
if you do not end your statements with a semicolon PHP will generate an error.