Learning PHP: Storing Basic Information
Now that you have a working PHP development environment, it's time to start learning some of the actual language.
In the next few articles, we will be taking a look at the fundamentals of the PHP language in preparation for creating your first script: a full-fledged form processor. This time, we will be focusing on the basic structure of PHP and taking a look at how it handles variables and data types.
Starting and Ending PHP Code Blocks
Take a look at the following simple PHP script:
In this example, PHP is embedded directly into an HTML document. Because
PHP and HTML can be mixed like this, every block of PHP code must be surrounded
by Start and End elements. These elements allow PHP to see which sections
of the page need to be parsed, and which can be ignored.
PHP recognizes four different versions of these sets:
1. <?php print "hello there!";?>
The first two versions are supported by PHP by default; however, you
will rarely see the second used in any scripts. Shorter and easier to
remember, the first is the preferred usage. The third method is also frequently
used, but requires the "short_tags" option to be enabled in the PHP configuration
file. Although many web hosts do enable this option, keep in mind that
any scripts written using them may not work in certain situations. The
final method will look familiar to ASP developers. Known as ASP Style
tags, this is the least-used method and requires the "asp_style" option
to be enabled.
You have also probably already noticed that most lines of PHP code end with a semi-colon. The semi-colon tells PHP when one statement is finished, so it can go on to evaluating the next. A closing PHP tag right after a statement has the same effect as a semi-colon:
<?php print "hello there!" ?>
Just like in HTML, PHP allows you to comment out lines of text. There are three ways to do this:
1. // This comments out a single line.
Commenting your script can become vital, especially when working on larger
projects and its a habit that you should develop now. Including information
about which blocks of code perform which functions can be a life saver
if you return to a project after you have forgotten the details. If you
are working on a collaborative project, having a well-documented script
also makes it easy for other people to understand script logic and your
PHP Building Blocks - Variables
If you have ever sat through a basic algebra class, you are probably already more familiar than you realize with what variables do and how to work with them.
Just as in math, variables in PHP are containers for bits and pieces of data. They are denoted by a dollar sign, and can be named anything beginning with a letter or underscore. Variable names can only contain letters, numbers, or underscores and are always case sensitive.
As a quick sample, try running the following script on your server:
When you run it, you will see that it prints "Hello there!" in your browser. Looking at the script, this makes sense: We begin by creating a variable called $var and assign a string value of "Hello there!" to it using the assignment operator (=). In the next line of the script, we use a print command to output the value of $var.
If you are making the leap to PHP after working with another programming
language such as C, keep in mind that you do not need to declare your
variables before using them. A variable in PHP is created automatically
as soon as a value is assigned to it.
Now, take a look at the following script:
Run this script and take a look at the output. Just like in the previous script, we created a variable. This time, we assigned a number to it instead of some words, and created a second variable as well. In the 3rd line, we added them together and assigned the sum to a variable called $sum. Because $var1 and $var2 are numbers, any mathematical operation can be applied to them, not just addition.
If you compare the two scripts, you will notice some slight differences in how the variables were assigned and in the way data was outputted to the browser. In the first script, the sentence assigned to the variable was surrounded by quotation marks, and the variable outputted to the browser was not. In the second, the exact reverse was the case.
Wondering why? Part of the answer lies with how PHP handles different
types of data.
PHP Building Blocks - Data Types
In PHP, every piece of data assigned to a variable is of one type or another. The types that PHP currently support are: Strings, Arrays, Integers, Floating Point Numbers, and Objects. For now, we'll just take a look at Strings and Integers, since both were used in the last two test scripts.
In PHP, a String is simply defined as a series of characters. They can contain letters, ASCII characters, numbers, and even other variables.
When you assign a string to a variable or print it out to the browser,
you must demark where that string begins and ends. Two of the most common
ways of doing this are:
1. Single Quotes:
2. Double Quotes:
Though the two methods resemble each other closely, there are slight differences in how they work. Try the following script:
$var = "This is a";
Based on what you know of PHP, you might expect that both lines would
return "This is a test". But take a look at the output:
This is a test
The major difference between double and single quotes is that contents
within single quotes are taken literally. If you have any variables within
them, they will not be translated into their values. This, however, will
|print $var . ' test';|
Since only strings need to be surrounded by quotes to be printed out, this is perfectly valid. Called the concatenation operator, the period works to append the right argument to the left, "gluing" them together and printing them both out.
In many instances, you may wish to print or assign a string which contains
quotation marks. When you do, if the quotation mark is the same as the
ones you are using to demark the string, it must be escaped by using a
backslash. Escaping a character lets PHP know that you wanted it to be
interpreted literally. For example:
$var = "I'm a string"; -- this is acceptable because you are using a single quotation mark within double ones. No escape character is needed here.
$var = 'I'm a string'; -- This would give an error because PHP sees the second single quotation mark as the end of the string, and the rest of the text following it as garbage that it can't understand.
$var = "I\'m a string"; -- This is the correct way to escape a quotation mark.
Just as in math, whole numbers, negative or positive, and zero are considered Integers. When you assign an integer to a variable, you do not use quotation marks:
$var = 1; -- this is an integer
One of things that make PHP so easy to use is its flexibility in how it handles types.
When you create a new variable, PHP automatically determines what type that variable is based on the data that you assigned to it. So, if you assign a string to a variable, the variable becomes a string. Likewise, assigning a function or an integer to a variable would cause the variable to become the associated type.
After creation, a variable can also change types on the fly based on
what context it is used in:
$var = "1"; -- $var is a string.
In the above example, $var was converted from a string to an integer because a numerical operation was performed on it. This is known as String Conversion.
If a string begins with numbers and also includes text, PHP will use the beginning set of numbers and completely ignore the rest of the text. If the string had not begun with a number, then PHP would have assumed $var was equal to 0 for the purposes of performing the operation. The end value of $var would have been one, instead of two.
If you want to see how this works in action, try running following script:
$var = "123 Texttexttext";
In the above script, the string variables were changed to integer variables
because an integer value was added, but that is not always the way it
$var = "33";
$newvariable is an integer, but $var remains a string because the result
of the operation was assigned to a new variable. Even though the original
variable remains the same type, this is still considered String Conversion.
In a process known as Type Casting, you can force PHP to treat a variable as one type or another when you create it:
$var = (int) "4"; -- $var is a int even though its surrounded by quotes, because you have defined it as such.
You can also specifically change the type of it is after having created it by using the settype() function:
$var = (int) "4";
By now, you should have a good feel for the basic syntax of PHP, and an
understanding of how to work with variables. In this article, you have run
into a few instances where various operators have been used: the assignment
operator to give a variable a value, the addition operator to add two values
together, and the concatenation operator. Next time, we will be taking an
in-depth look at more of the operators commonly used in PHP. Stay Tuned!
Keep in mind that while there are some occasions where you may need to manually set or change the type of a variable, PHP is very accurate in dealing with them in the proper context and typically you should let it do the work.
If you are feeling a little confused, don't worry. Generally, much of this takes place behind the scenes. As you work more with PHP, you will gain a better feel for how types come into play and how to work with them.
| Things to Remember:
Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.
# # #