Variables

Before I show you any more examples I had better introduce to you the different kinds of variables we have in PHP. Variables are what you use to store something for later use. You might want to refer to your age, so it would be nice to define the age only once, and then just refer to it later. When your age changes, you just update the definition of your age, and then all other calculations that refer to the age are also updated. All the names of the variables must start with the $ character. After that there must be a letter. The rest of the name can consist of both letters and numbers. Here are three examples of valid names for a variable: $name, $address2 and $colour_30. As you can see, you can also use the _ (underscore) character in your names. It is often used as a replacement for spaces, since they are not allowed.

To use a variable you have to assign a value to it. It is done this way, where we assign the string “Martin” to the variable $name:

$name = 'Martin';

The name of the variable is on the left of the = sign and the new value of the variable is on the right. Here we assign the integer value of 18 to the variable $age:

$age = 18;

There are several different types of variables. You have already met the integer and string types. Lets start with the integer type.

Numbers

Dealing with numbers is easy with PHP. You can just use them as you like. All the normal rules about precedence apply, so you can write something like this:

$a = 4;
$b = 7;
$c = 2 + 3 * $a + 5 * $b  // Evaluated as 2 + (3 * 4) + (5 * 7) = 49.

As you can see, everything works as you would expect. Any variables are automatically substituted with their values. This is done before the new value is stored in the variable on the left side of the =-sign. This means that you can do something like this:

$a = 5;
$b = 10;
$a = (2 * $a + 5)/$b; // Evaluated as $a = (2 * 5 + 5)/10 = 1.5

Strings

To assign a string to a variable, you must use quotes. You can choose between single quotes (') or double-quotes ("). The kind of quote you should choose depends on the string you work with in a given situation. There are some differences between the two types of quotes. The first code,

$first_name = 'Martin';
$greeting1  = "Hello, my first name is $first_name.";
echo $greeting1;

produces “Hello, my first name is Martin.“, whereas this code

$last_name  = "Geisler";
$greeting2  = 'Hello, my last name is $last_name.';
echo $greeting2;

gives “Hello, my last name is $last_name.” as output.

“Why was it only the first string that worked properly?”, you might ask. The answer is that when using double-quotes, PHP performs what is known as variable-expansion. That means that PHP expands (substitutes) $first_name with it’s value, just as you saw it when using numbers. The result is that the string stored in $greeting1 is “Hello, my name is Martin.” (the double-quotes are not part of the string stored in $greeting1). When assigning to $greeting2 using single quotes, PHP doesn’t substitute any variables and $greeting2 ends up with “Hello, my last name is $last_name.“.

But there’s more magic with the double-quotes. They will also expand other special characters, such as newline-charecters (\n). This mean that the following string:

echo "Martin\nGeisler";

will look like this in the source of the page:

Martin
Geisler

You’ve met the echo statement before (in the “Hello World” example) and it just outputs the string after it to the webbrowser. As I said earlier there’s no trace of the PHP code, but notice that there’s a linebreak between the two words. (The linebreak can only be seen in the source of the page, because the webbrowser treats the linebreak as a normal space — use something like <br/> to force a linebreak using HTML) You should also notice that there’s no space before or after the \n-character. Because you use the \-character to indicate that the next character is special, you have to write \ when you want to have a single \. The backslash (\) is called an escape-character, since it makes the characters escape from their normal role. The double-backslash-trick makes the escape-character escaped.

If you want to have a $-charactar in a string enclosed in double-quotes, you’ll need to escape it, or else PHP will look for a variable, since all variables start with a $.

This string will give you a little problem:

$name = "Martin "mg" Geisler";

If you try it out, you’ll get an error. That’s because the parser expects the string to stop after the second double-quote, just before the word mg. The rest of the line is just garbage to the parser so it complains loud. Perhaps it would help if we escaped the double-quote? Exactly! The following string is correct:

$name = "Martin "mg" Geisler";

The same applies if we had been using single quotes throughout the string. But there’s another way to solve the problem. You could quote the string with single quotes and then use as many double-quotes within the string as you would like. Or you could do the inverse, and enclose the string in double-quotes and use single quotes in the string. This solves a problem you would have when outputting HTML-code with lots of double-quotes:

echo '
<a href="mailto:mgeisler@mgeisler.net">
  <img src="mg.png" width="16" height="16" alt="me" />
</a>';

If we had quoted the string with double-quotes, we would have had to escape all the other double-quotes. But on the other hand, in the string above PHP wouldn’t do any variable-substitution. Also, the escape-characters will not be understood, so you can’t write \n in a string enclosed by single quotes. Instead you can put the newlines directly into the code, as I’ve done in the example. The final output will still contain those newlines. Of course the newlines aren’t strictly necessary, but put them in anyway — you’ll be glad you did when you have to debug your scripts by reading through their HTML output! (And believe me… sooner or later you will have to debug your PHP scripts… and then it’s nice to have them make some output that’s digestable for humans too :-)

It’s only when you’re evaluating expressions (such as in assignments and echo statements) that the difference between single and double-quotes comes into play. After the assignment is done, you wont be able to tell how the string was produced. Consider this code:

$first_name = 'Martin';
$last_name = "Geisler";
$var1 = "$first_name $last_name";
$var2 = 'Martin Geisler';

The two variables $var1 and $var2 will both contain the string Martin Geisler after the evaluation, without any sign of all the different kinds of quotes that were used in the construction and PHP will not make any distinction between the values stored in the two variables.

Concatenation

If you want to concatenate (string together) two strings you use the .-character (a dot or full stop) like this:

$first_name = 'Martin';
$last_name  = 'Geisler';
$full_name  = $first_name.$last_name;

Now $full_name will contain the string “MartinGeisler“. That’s probably not what you wanted, it would be better with a space between the two words. To do this, you execute the following code:

$full_name = $first_name . ' ' . $last_name;

Notice that the space between the variable-name and the dot is ignored — it’s the string with the space that’s important. You use the dot (full-stop) each time you have two strings that you need to put after one another.

But you’ve also seen how this could be solved using variable-substitution. This is often easier to read, just remember to use double-quotes around the string. So this code gives the same result:

$full_name = "$first_name $last_name";

When using variable substitution you might run into a little problem. The problem occurs when you want to substitute a variable in a string and have text immediately after the variable. You have to delimit the name of the variable somehow. Using curly braces is the solution as shown in this code:

$noun = 'car';
echo "One $noun, two ${noun}s";

Here we’re playing with English words in plural form. The first occurrence of $noun is substituted correctly, even when it’s followed immediately by a comma because you cannot have a comma in the name of a variable. But you could certainly have a variable called $nouns, so we have to use curly braces to indicate that we want the variable called $noun and not some nonexistent variable called $nouns.

Arrays

Arrays are a single variable that can hold a number of different values at the same time. These sub-variables are indexed either by a number (starting from zero) or by a string. To access the different values you specify the index using brackets after the name. It works like this:

$name[0] = ‘Martin’;
$name[1] = ‘Geisler’;

Now we have made an array, and filled in the two first slots. Notice that the numbering starts at zero and not one — this is normal with most programming languages and something which one just has to learn. We can recall the values like this, using the same notation as when you stored them:

echo $name[0] . ‘ ‘ . $name[1];

If you don’t care which slot you get when you assign to an array, then use a pair of empty brackets after the name:

$data[] = ‘Martin;
$data[] = ‘Geisler;
$data[] = 18;

This filled the first three slots of the array, numbered 0, 1, and 2. When you want to retrieve the information again, you must specify which slot you want access to. But you can also identify the different slots by name using a string. This makes everything much more readable and easy to understand:

$data['first name'] = ‘Martin’;
$data['last name']  = ‘Geisler’;
$data['age']        = 18;
echo ‘Hello ‘ . $data['first name'] . ‘! ‘ .
     ‘We know that you are ‘ . $data['age'] .
     ‘ years old.’;

Notice how I broke the last line to make it shorter and how I used the dot operator to glue the strings together with the variables, inserting spaces as needed. The parser will ignore all whitespace outside the strings, and the result is:

Hello Martin! We know that you are 18 years old.

Also note how I split the string up into its individual pieces. This is often the easiest way to deal with associative arrays. Another possibility is to use variable substitution with curly braces like this:

echo "Hello {$data['first name']}! ” .
     “We know that you are {$data['age']} years old.”;

This code gives the same result. You can put complex expressions inside such a set of curly braces. This includes accessing elements in multidimensional arrays and object properties.

Please do use descriptive names for the indices in your arrays. It makes the code much more clear, and helps to indicate what the different slots are intended for.

If you know all the values you can define the above array using an alternative syntax using only one assignment:

$data = array('first name' => 'Martin',
              'last name'  => 'Geisler',
              'age'        => 18);

If you don’t need named indices (just numbers) then simply write

$data = array('Martin', 'Geisler', 18);

The array() language construct can be used whenever you need an array in your code — for example together with the str_replace() function which does a search-replace in a string. In its simplest form it just takes three strings as arguments: the string to search for, the string to replace with, and the string in which the search-replace operation will take place. But because one often want to do several search-replace operations on the same string, or do the same operation on several strings, the function also takes arrays of strings in each argument. In that case the function will act as if it had been called several times using each pair of entries from the arrays. An example could be:

$some_string = 'Elvis has left the building!';
$result = str_replace(array('Elvis', 'left', 'building'),
                      array('You', 'entered', 'house'),
                      $some_string);

Now $result will contain “You has entered the house” where “Elvis” was replaced by “You”, “left” by “entered”, and “building” by “house”.

Now that we have seen how to assign values to variables, let’s have a look at the different control structures in PHP.

7 Comments

  1. Scott:

    Martin,

    Thanks for actually taking the time to write this tutorial -Everytime I teach myself a new language, new app or server configuration I swear I’m going to write a tutorial to save others some learning pains. (but I never do)

    Anyway, as far as I can tell the newline “\n” as you used it above doesn’t work when passed to HTML. I had to use “”.

    Thanks again for your efforts.

    Scott

  2. Martin Geisler:

    Thanks for the feedback! I’m glad that my tutorial is still useful.

    As for the problems with the newline character, would it then be the typical problem with having to use <br/> in the source to get a linebreak in the browser? From the feedback I’ve gotten I can tell that this is a very common mistake…

  3. Umer:

    I have a form that returns a string like: “xyz, abc, def” and I want to put single quotes around each of these values before using this string in a query? how can that be done in php?

  4. Patrick:

    Thanks for the tutorial. Time is money and you are saving all of us time, it’s like giving away money :-) Thanks

  5. Vaughn:

    These two appear to be the same to me

    This string will give you a little problem:

    $name = “Martin “mg” Geisler”;
    If you try it out, you’ll get an error. That’s because the parser expects the string to stop after the second double-quote, just before the word mg. The rest of the line is just garbage to the parser so it complains loud. Perhaps it would help if we escaped the double-quote? Exactly! The following string is correct:

    $name = “Martin “mg” Geisler”;

  6. Benny:

    Martin, I am really impress with what you have here. Your site have made me to understand some of the challenges I have had so far in my site design and twitching. It’s the best tutorial on php that I have seen so far on the ‘Net. (As a result, I have reviewed this page on Stumbleupon to create more visibility for you.)

    Maybe I should ask this question here.. “What is the best way to implement my ‘Homepage’ and ‘Contactpage’ on Wordpress at the moment using PHP? You could view my site Sirius Forex to see what I mean. Thank you.

  7. Martin Geisler:

    Cool, thanks for the review. As for WordPress, then you might be able to find a plugin for a contact page, I don’t know. Or you can ask in the WordPress forums where the real experts hang out — I’m just using a stock WordPress installation here :-)