PHP syntax is a lot like the syntax of C, C++, C#, Java, JavaScript, ActionScript, and other C-like programming languages. But there are some interesting and significant differences, too. So if you have any prior experience with the C-like languages, be careful, and pay close attention!
I will be taking a lot of what we discuss in this section from the PHP.net site at http://www.php.net/manual/en/language.basic-syntax.php but will also attempt to clarify their information.
When PHP reads and interprets a Web page, it looks for opening and closing PHP tags, which tell PHP to start and stop interpreting the code between them. This interpretation process is called "parsing". Parsing allows PHP to be embedded in all sorts of different documents, since everything outside of a pair of opening and closing PHP tags is ignored by the PHP parser. Most of the time you will see PHP code embedded in HTML documents.
The beginning PHP marker looks like this:
<?php
The ending PHP marker looks like this:
?>
You will put your PHP code between these two markers.
You may have as many sections of PHP code in your page as you need. Please note carefully that each PHP section must be separate from the others, but you can have multiple PHP sections.
And please note carefully that your PHP code sections can be just about anywhere in and among the HTML code in your page. This feature of PHP is, in fact, one of its most powerful capabilities.
Please note these points about the code below:
Here is an example of PHP code embedded in an HTML page. There is only one PHP section in this page, but there can be multiple PHP sections in an HTML page. This is page syntaxExample1.php:
You can see the page below running on the server here.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Syntax Example 1</title>
<link rel="stylesheet" href="myStyles.css">
</head>
<body>
<div id="mainDiv">
<p class='normal'>This paragraph will be ignored by the PHP parser/server, and sent directly to the HTML page.</p>
<?php echo "<p class='PHPstuff'>This paragraph will be parsed and output to the HTML page by the PHP parser/server.</p>\n"; ?>
<p class='normal'>This paragraph will also be ignored by the PHP parser/server, and sent directly to the HTML page.</p>
</div>
</body>
</html>
You can put "comments" in your PHP code, to help you remember why you used the statements that you put into your code. Comments are totally ignored by the PHP parser. PHP comments can have one of two possible formats:
Here is an example of some PHP comments. This is page syntaxExample2.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PHP Syntax Example 2</title>
<link rel="stylesheet" href="myStyles.css">
</head>
<body>
<div id="mainDiv">
<h3>Examples of PHP Comments</h3>
<h5>(You won't see them in the browser!)</h5>
<?php
echo "<p>This is paragraph 1.</p>\n"; // This is a single-line comment.
echo " <p>This is paragraph 2.</p>\n"; /* This is a multi-line comment.
It continues onto several
lines. */
?>
</div>
</body>
</html>
You can see the above code running on the server here.
A variable is a named storage area in the computer's memory. For our purposes, you just need to know that you can store information in a variable, and get that information out of the variable later.
PHP gives you the power (I assure you, such power exists!) to create your own variables. You create a variable like this:
<?php
$userName = "Jim";
?>
There are some important considerations that you should follow when you name your variables:
You should note carefully that the equal sign in the code above means "assign a value to". It does not mean "equals" in PHP. You can read the above line of code something like this:
"The value 'Jim' is assigned to the variable $userName."
OR
"The variable $userName gets the value 'Jim'."
OR
"The variable $userName is assigned the value 'Jim'."
These are all different ways of communicating the same concept: Using the assignment operator, which is the equal sign.
You should also note carefully that the line of code above ends in a semi-colon. This special character is used in PHP to end an instruction (also called a statement). This is one of the basic syntax rules in PHP.
There are basically two kinds of information that you can put into a variable:
print "<input type='text' name='firstName' />";
or
print '<input type="text" name="firstName" />';
Sometimes you need to combine strings or string variables into a single, larger string. The technical term for combining strings (text) in PHP is concatenation.
The concatenation operator in PHP is the period (.).
So, for instance, you could combine some string variables like this: This is page concatenation.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Concatenation</title>
<link rel="stylesheet" href="myStyles.css">
</head>
<body>
<div id="mainDiv">
<?php
// Example one: concatenation
$varOne = "George";
$varTwo = " of the ";
$varThree = "Jungle";
$varConcatenated = '<p>' . $varOne . $varTwo . $varThree . "</p>\n";
echo $varConcatenated;
// Example two: simple interpolation
$varInterpolated = " <p>$varOne$varTwo$varThree</p>\n";
echo $varInterpolated;
// Example three: complex (curly-brace) syntax interpolation -- optional for non-array variables
$varInterpolatedWithBraces = " <p>{$varOne}{$varTwo}{$varThree}</p>\n"; //braces are optional in this situation
print $varInterpolatedWithBraces;
?>
</div>
</body>
</html>
which would put this string value into the page:
<p>George of the Jungle</p>\nthree times.
You can see the above page displayed in your browser here.
Sometimes it is advantageous to store code that you will be using in multiple Web pages, in a separate file called an "include file". You can "include" the code that is in this "include file", in each main page that you need it in.
When the PHP processor reads and processes a main page which has an "include" statement in it, it adds the code that is in the "include file" to the code that it is processing for the main page; and processes it, as if the code that is in the "include file" were actually typed into the main page.
When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the include file, and resumes PHP mode again at the end. For this reason,...
Any code inside the include file which should be executed as PHP code must be enclosed within valid PHP start and end tags in the include file itself.
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
The syntax of the "include" statement that goes in the main page (which is including and using the code in the "include file") looks like this:
include "filename.php";
There is a related statement, called require, that functions like include but throws a fatal error if the included file is not available. The include statement throws a warning, but not an error, if the included file is not available.
Here is a sample of a file that uses an "include file". This is page testInclude.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test a PHP Include File</title>
<link rel="stylesheet" href="myStyles.css">
</head>
<body>
<div id="mainDiv">
<?php
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
echo "<h3>Here is the bad stuff:</h3>";
echo "<p>";
echo "A $color $fruit"; // A
echo "</p>";
include 'vars.php';
echo "<h3>Here is the good stuff:</h3>";
echo "<p>";
echo "A $color $fruit";
echo "</p>";
?>
</div>
</body>
</html>
Here is the "include file", vars.php:
<?php $color = 'green'; $fruit = 'apple'; ?>
You can see the sample include file running here.
Please note these points about the above code:
The type of quote you use in PHP (single or double) can make an important difference in how PHP interprets some of the special characters that are called escape sequences (characters), and in how it handles variable names in the string:
| Sequence | Meaning |
|---|---|
| \r | Carriage Return (CR) |
| \n | Linefeed (LF) |
| \t | Horizontal Tab |
| \\ | Backslash |
| \$ | Dollar Sign |
| \" | Double Quote |
You can display the value that a variable contains, along with other text if you wish, with the print statement. The print statement works almost exactly like the echo statement that we saw earlier in this handout.
This line of code:
print "Hi, $userName";
will put this text into the Web page (assuming that we have already created the $userName variable and have assigned the string "Jim" to it, as we did above):
Hi, Jim
Because the output of the print statement becomes part of the HTML information that is sent to the browser, you can even include HTML tags in the output of a print statement.
Also, as a historical note: Because a lot of the original "C" programming language, which PHP is based on, was developed during the time when teletype machines or printers were used for displaying the results of a program's calculations, we still have the name of this command as print. But in the HTML and Web world, it really means that the information will be included in, and possibly displayed in, a Web page. So "print" doesn't mean "print" from a printer, it means to output the information to the HTML page.
You will see many PHP pages that use echo instead of print to put information into the page. So the question naturally comes up, "When should I use print, and when should I use echo?" And also, "What is the difference?"
There is a good discussion of the differences at http://stackoverflow.com/questions/234241/how-are-echo-and-print-different-in-php, which I will summarize here:
echo "Hello", "there", ", number", 1, "!";which get concatenated into the page.
print "Hello there, number 1!";
print ("Hello there, number 1!");
and
echo ("Hello there, number 1!");
Many times in PHP, you will need to treat multiple statements as a single block or group of code. Most programmers call such a group of statements a "code block" or "block of code". You create a code block in PHP with curly braces.
For instance, when you test a condition in PHP, you use the if statement. (We will talk about condition testing in a future class, so please don't panic about the details of "if".) When you need to run a group of other statements based on the results of the condition test, you use curly braces to create that group of statements.
Here is a page which uses one of these "if" statements and two code blocks. This is page showBlock.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>PHP Blocks</title>
</head>
<body>
<div id="mainDiv">
<?php
$myVar = 1;
if ($myVar == 1)
{
echo "The sun is shining.";
echo "<br />";
echo "Let's all go out and play!";
}
else
{
echo "It is raining.";
echo "<br />";
echo "Let's go jump in the puddles!";
}
?>
</div>
</body>
</html>
You can see the above code running on the server here.
Please note these points about the above code:
PHP has a very interesting, special quoting mechanism known as multi-line strings.
You can put as many multi-line strings into your PHP code as you need. Just make sure you finish making one before you start another one.
Here are some rules for creating a multi-line string. Please refer to the sample code below:
Look at this sample page, which creates a multi-line string in the variable $verse: This is page rowYourBoat.php.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>A Multi-Line String</title>
</head>
<body>
<div id="mainDiv">
<h1>Row Your Boat</h1>
<?php
$verse = <<<HERE
Row, row, row your boat<br />
Gently down the stream<br />
Merrily, merrily, merrily, merrily<br />
Life is but a dream!<br />
<br />
<br />
HERE;
print "<h3>Verse 1:</h3>";
print $verse;
print "<h3>Verse 2:</h3>";
print $verse;
print "<h3>Verse 3:</h3>";
print $verse;
?>
</div>
</body>
</html>
You can see the above code running here.
Some variables require a special syntax in order to be expanded (interpolated) into a string. Specifically, ARRAY variables will not be expanded into a string unless they are surrounded by curly braces. This syntax is usually referred to as complex syntax or complex (curly) syntax.
We will talk about arrays in more detail later in the semester.
For now, note that arrays are like indexed lists of items. You refer to array variables with the name of the array followed by a set of square brackets which contains the name of the item in the array that you want, as a quoted string.
For example, if you have an array variable named strangeAnimalLocations, and you want to find out where aardvarks live, you would get the location of an aardvark with this kind of notation:
livingSpace = strangeAnimalLocations["aardvark"];
Later in this handout, when we talk about HTML forms, we will see that PHP automatically creates an array variable that contains the information that was sent from a form, for use in the form's PHP action page. If the form's method attribute is "post", the array variable that is automatically created by PHP for use in the PHP action page is $_POST. Note that there is an underscore at the beginning of the variable's name, and the name is in uppercase letters.
Here are a few examples of using curly braces for expanding array variables in strings:
First, if we wanted to display the living place of aardvarks in our PHP page, we could use code like this:
echo "Aardvarks live in {strangeAnimalLocations['aardvark']} most of the time.";
Also, for example, if we wanted to display the contents of the "UserName" input field from an HTML form, in our PHP action page, we could use code like this:
echo "Thank you for your comments, {$_POST['UserName']}. We will be in touch shortly.";
In PHP, you can perform the standard operations with numbers, which we will see in the next section, with symbols (characters) that are referred to as operators. An operator does something with the two values that come before and after the operator itself.
Here is a table of the standard arithmetic operators in PHP:
| Operator | Character/Symbol | Description |
|---|---|---|
| + | Plus Sign | Addition |
| - | Hyphen (Minus Sign) | Subtraction |
| * | Asterisk | Multiplication |
| / | Forward Slash | Division |
You create numeric variables just like any other variable in PHP. You eventually will need to assign a value to the variable name.
Here is a sample page that does some numerical calculations, using the operators that were shown in the previous section. This is page numericVariables.php:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="myStyles.css">
<title>Numeric Variables and Operators</title>
</head>
<body>
<div id="mainDiv">
<h1>Numeric Variables and Operators</h1>
<?php
$x = 3;
$y = 5;
print "$x + $y = ";
print $x + $y;
print "<br /><br />";
print "$x - $y = ";
print $x - $y;
print "<br /><br />";
print "$x * $y = ";
print $x * $y;
print "<br /><br />";
print "$x / $y = ";
print $x / $y;
?>
</div>
</body>
</html>
You can see the above code running here.
Please note these points about the above code: