PHP Tutorial – Basic Syntax

0024-FIIn the Introduction article we wrote a simple PHP script that prints “Hello, world!” without really explaining how it works. In this article we’ll take a look at some basic PHP syntax topics that explain how the PHP interpreter treats source files containing a mixture of HTML and PHP. We’ll discuss tags that the PHP interpreter recognizes as delimiters of PHP code. We’ll look at the concept of expressions and statements in PHP and what the echo statement does. We’ll also take a look at how to embed comments in your programs in order to document the code.

Tags

The first script that I presented in the last article is reproduced below. Recall that this script was stored in a file called index.php.

<?php
echo "Hello, world!\n";
?>

Whether the PHP interpreter is executed from the operating system command-line or from within a development tool like NetBeans, the result is the same: the script displays the text “Hello, world!” followed by a newline character. The newline character, represented by “\n” in the string, causes a “carriage return” so that subsequent output, if any, will begin on the next line.

Let’s examine this short program line by line. On line 1 we see the PHP opening tag, <?php. When the PHP interpreter reads this sequence of characters it will expect PHP script code to follow. It will then read, parse, and execute all subsequent statements until it finds the PHP closing tag sequence ?>, which we find on line 3. Any characters that lie outside of the opening and closing tags is just displayed without change.

In this simple script there is only one PHP statement between the opening and closing tags. This statement begins with the keyword echo followed by a sequence of characters within double-quotes. The character sequence within double-quotes is called a string, which is one of the data types in PHP, along with integers, floating point numbers, and several others. We’ll discuss all of the PHP data types in a later article.

As it happens, the PHP interpeter recognizes three other delimiting tag pairs besides <?php ... ?>. The first is called the short tag, which is comprised of <? and ?>. The use of the short tag is discouraged because it requires the short_open_tag option to be enabled in the interpreter’s initialization file. The example code using the short open tag is shown below.

<?
echo "Hello, world!\n";
?>

With the short_open_tag directive set to Off, the PHP interpreter will just ignore the code and display each line as if the tags were not there. This output is shown below.

<?
echo "Hello, world!\n";
?>

Another tag set that PHP can interpret is the ASP tag format, <% ... %>. In order to make the interpreter recognize these as PHP code delimiters, the PHP initialization directive asp_tags must be enabled. As with short tags, the use of ASP tags is also discouraged since the initialization directive may not be enabled on all servers. The example above using ASP tags would look like this:

<%
echo "Hello, world!\n";
%>

Without the asp_tags directive enabled, the output would again just be the code itself as if the tags were not present:

<%
echo "Hello, world!\n";
%>

PHP also recognizes the tag pair <?= ... ?>. This is called the echo short tag and it is just a shortcut for <? echo ... ?>. As such, it cannot be used for arbitrary PHP code. However, this tag is useful if you just need to use a PHP expression to provide an attribute value in an HTML tag. The availability of this tag used to be controlled with the short_open_tag PHP directive, but since PHP 5.4 it will be recognized even if short_open_tag is not enabled. However, you should still avoid it if you don’t control the version of PHP on which your program will be deployed. The example above would look like this if you use the echo short tag:

<?= "Hello, world!\n"; ?>

Notice that the echo keyword is removed altogether when using this tag pair.

Similarly to the echo short tag, PHP recognizes echo ASP echo tag, <%= ... %>. This tag pair is short for <% echo ... %>, however, it is controlled by the asp_tags directive in all versions of PHP. It should also be avoided for same reasons as the ASP tag format.

The final PHP tag pair is the HTML <script> tag. This tag can also be used for other languages such as Javascript. In order to inform the interpreter to expect PHP code, you need to specify it with the language attribute of the tag. Here is an example:

<script language="php">
echo "Hello, world!\n";
</script>

While the <script> tag is always available, it is more cumbersome than <?php ... ?> so you won’t see it used too often. Considering the limited availability of the short tag syntax, the version dependence of the echo short tag syntax, and the greater complexity of the <script> tag, it is generally preferrable to stick with the <?php ... ?> tags.

When using the <?php ... ?> syntax in a file with only PHP (that is, no HTML) the closing tag is optional. In fact, it is recommended that you don’t include it in these cases. This has to do with the interpreter exiting from PHP mode and potentially buffering trailing whitespace characters that may be present after the final ?> tag. Given this recommendation the example we’ve been looking at can just be written as:

<?
echo "Hello, world!\n";

Now let’s take a look at the second example in the last article where PHP code is embedded within an HTML web page (shown below). When the PHP interpreter begins reading the file, it will output all of the characters up to <?php sequence on line 8. At this point the interpreter will begin parsing and executing PHP code until it reaches the closing ?> sequence (also on line 8). Even though this particular example has both the opening and closing tags on the same line, this is not a requirement. Any amount of PHP code can be enclosed by the <?php and ?> pair and there can be any number of tag pairs in the script. Once the closing tag is encountered, the interpreter will resume outputting characters until it reaches the end of the file.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Hello, world!</title>
    </head>
    <body>
        <h1><?php echo "Hello, world!"; ?></h1>
    </body>
</html>
Note: If you are using NetBeans as recommended in the article mentioned above, you can switch to the Web run configuration and view the output of the script in your web browser. As demonstrated in that article you can then view the page source by right-clicking the browser window and selecting View Page Source from the context menu.

In the output of this script below, you can see that the echo statement was executed by the interpreter and the result of executing the statement was embedded within the HTML at the point where the <?php and ?> tag pair was encountered.

PHP output is inserted into the HTML

Output from the echo statement is inserted into the HTML in place of the <?php and ?> tags.

Of course, this particular example could just as well have included the “Hello, world!” message directly in the HTML since it never changes. Generally, embedded PHP code would generate dynamic output that varies with each page refresh. Consider the example below:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Current Time</title>
    </head>
    <body>
        <p><?php echo "The current time is: ", date("g:i:s a"); ?></p>
    </body>
</html>

This PHP web page calls the PHP date() function to get the current time. I’ll discuss PHP’s calendar and date functions in detail in a later article, but for now, realize that the call will retrieve the time from the server operating system and display it in accordance with the format string that is passed as an argument. In this case we pass the format string “g:i:s a” which returns the time in HH:MM:SS format with an AM/PM indicator.

Note: When you run the script above with either the command-line or web run configuration you will likely get a long error message from the PHP interpreter complaining that you haven’t set your timezone. The timezone setting is found in the PHP initialization file called php.ini; there are two of them: one for the command-line interface and one for the Apache Web Server. On the default Ubuntu installation, the command-line configuration file is located in the directory /etc/php5/cli and the Apache version is located in /etc/php5/apache2. In each file you need to find the line that reads:;date.timezone =

Uncomment the line by deleting the semicolon at the beginning and then enter your timezone after the equal sign. The full list of timezones can be found at www.php.net/timezones. Find a country/city pair that is in your same timezone. For example, on the US East Coast you could use America/New_York, in which case your php.ini files would contain the line:

date.timezone = America/New_York

When you view the resulting page in the web browser, you will see output similar to that shown below. Each time the browser is refreshed, the PHP code will be re-executed and the time will advance.

The current time updates on each browser refresh

Output from the PHP date() function is updated with each browser refresh.

Expressions and Statements

Now that we have seen the PHP tags in which code is embedded, let’s look at the code itself. An expression is a sequence of characters which is evaluated to produce some value. For example, when PHP evaluates the expression “4+3” it will return the value 7. This expression combines the operands 4 and 3 with the operator + to produce the sum of 7. In this case the operands and resulting value are all integers, but PHP can work with other data types as well. I’ll discuss all of the data types and operators in later articles.

A statement is a collection of expressions that are evaluated and acted upon by the interpreter. For example the statement:

echo 4+3;

will cause PHP to first evaluate the expression 4+3 to get the value 7 and then output that value. The statement

echo 4+3*6;

will cause PHP to first evaluate the expression 3*6 to get the value 18, then evaluate the expression 4+18 to get the value 22, then output that value. The reason that 3*6 is evaluated first is that the multiplication operator (*) has a higher precedence than the addition operator (+). I’ll review all of the operators and their relative precedence in a later article.

As shown in these examples statements in PHP are terminated with semicolons, however, you can omit the final semicolon before the PHP closing tag. For example, the statement

<?php
echo "Hello, world!\n";
?>

and

<?php
echo "Hello, world!\n"
?>

are both valid.

I’ll be using echo a lot when showing examples so let me tell you a little more about it. The echo keyword causes PHP to just display whatever is passed to it until the end of the statement. You can pass it an arbitrary number of expressions to display, separating them with commas. For example, the two echo statements below display the same value.

<?php
echo "Hello, ", "world", "!";
echo "Hello, world!";
?>

The echo keyword can also be used with function call syntax, so the following statements both produce the same value:

<?php
echo "Hello, world!";
echo ("Hello, world!");
?>

The echo statement can also display values of any data type. For example, the code:

<?php
echo "The value of 4+3*6 is ", 4+3*6;
?>

produces the output

The value of 4+3*6 is 22.

There are many other functions in PHP that display expression values. I’ll review most of them in later articles.

Comments

In addition to executable statements, you can include comments in your source code. Commenting your code makes it easier for you and others to maintain it later. PHP supports three types of comments: C style, C++ style, and shell style.

C style comments begin with the character sequence /* and end with */. Everything between the two delimiters is ignored by the interpreter. Using this style of commenting allows you to include multiple lines of comments in your source. For example, the following code contains a comment at the top of the script to explain what it does.

<?php

/* This is a multi-line comment that explains what my PHP script
does in detail. It describes the data structures and algorithms
that I use to implement my design. */

?>

You will often see a variation of this type of comment formatted as shown below. The extra asterisks at the beginning of each line help to make the comment stand out from the surrounding code.

<?php

/* This is a multi-line comment that explains what my PHP script
 * does in detail. It describes the data structures and algorithms
 * that I use to implement my design.
 */

?>

These types of comment blocks are useful for explaining sections of code in a long script. Some IDEs such as NetBeans will help you create this type of comment by automatically inserting the asterisks as you type.

Note, that you cannot nest comments of this type. For example, if you have a script like this:

<?php
echo "Hello, world\n";   /* print greeting */
echo "How are you?\n";   /* print question */
?>

you might decide to comment out both statements so they won’t execute. The easy way to do it is to wrap the statements with C style comment delimiters like this:

<?php
/*
echo "Hello, world\n";   /* print greeting */
echo "How are you?\n";   /* print question */
*/
?>

However, you will recieve a parse error when you try to run it. The reason is that the first comment ends when the first */ sequence is encountered after print greeting. This comments out the first echo statement. The second echo statement then has a valid comment with opening and closing delimiters. However, there is then another */ delimiter at the end of the script with no corresponding beginning delimiter.

The second kind of comment supported by PHP is the C++ style comment. This style uses the delimiter // to begin the comment and the end-of-line to end it. Everything from the // to the end of the line is ignored by the interpreter. Using this style of commenting in the code from the last example would look like this:

<?php
echo "Hello, world\n";   // print greeting
echo "How are you?\n";   // print question
?>

This style of comment is useful for explaining what’s happening on a specific line of code. It is possible to nest C++ style comments within C style comments. Given the same scenario as earlier where you want to comment out both lines you can wrap the entire block with /* and */ comment delimiters as shown below.

<?php
/*
echo "Hello, world\n";   // print greeting
echo "How are you?\n";   // print question
*/
?>

This will work as intended because the outer comment has different delimiters than the line comments so the parser will not get confused.

The third style of comments supported by PHP is the shell style. This type of comment begins with the delimiter # and continues to the end of line. Using the same example as before, the code would look like this:

<?php
echo "Hello, world\n";   # print greeting
echo "How are you?\n";   # print question
?>

As with C++ style comments, shell style comments can be nested inside C style comments like this:

<?php
/*
echo "Hello, world\n";   # print greeting
echo "How are you?\n";   # print question
*/
?>

This article provided some basic syntax that you will use in all of your PHP programs. We looked at the various tags that determine where a PHP program begins and ends. Of the different tags that PHP supports, only the <?php ... ?> syntax and the <script language="php"> ... </script> syntax is always available on all versions of the interpreter. We explored the concepts of expressions and statements in PHP and found that statements end with a semicolon, which is optional for the last statement before a closing PHP tag. Since we use the echo statement for most of our examples, we took a look at a few of its properties. Finally, we examined the different ways of including comments in your code to explain to others (and to remind yourself) what your code is supposed to do and how it works.

In the next article we’ll look at a component of most every program, the variable.

Speak Your Mind

*