Have fun with variables
You have learned how to handle variables in Part I. Since then, you may have noticed that you need them in all your PHP scripts.
This chapter aims at teaching you some techniques to handle the variables even more better:
1. First, we'll deal with concatenation. You just have to get used to it, and it will clean up your code.
2. Then we'll see some ready to use functions in PHP allowing to work on variables. These are really convenient (and easy to use) tools, which will soon become vital for you
3. And to finish with a flourish, I will teach you a twisted thing: variable variables!
I hope you thrill-seekers are ready!
Concatenation.
Dreadful word again, which seems to be the privilege of computing gurus. It is in fact a mere full stop. You read me right, a measly full stop like this one
.
Let me show you an example. Look at this code, which might remind you of this lesson's first chapters.
Code: PHP1
2
3
4 | <?php
$name = "Mateo21";
echo "Hi $name, how are you?";
?>
|
Not too hard so far, right?
It will display:
Hi Mateo21, how are you?
Well, if you want to know a good one, the code below will produce
exactly the same result:
Code: PHP1
2
3
4 | <?php
$name = 'Mateo21';
echo 'Hi ' . $name . ', how are you?';
?>
|
And that is what a concatenation is. You have noticed the full stop, haven't you? It enables to make the link between your variable and the rest of your text.
You may have been surprised also by the fact that I am using apostrophes instead of inverted commas to mark off a text-area. Although the use of inverted commas is still possible, apostrophes look cleaner with concatenations.
From now on, we will be using concatenation only. Besides, we will be using concatenation and apostrophes most of the time. I advise you to do the same, we'll see it has some advantages.
But... But... Are you making fools of us? Now you want us to use your concatenation and apostrophes, after having taught us to do things differently?
Anyway, I don't see what's so brilliant about concatenation...
Here are some good questions!
You should know that, in a prior version of this PHP tutorial, I was evoking concatenation right from the beginning (in the first chapter on variables). And apparently, it was problematical: it was just too many things at the same time for a beginning.
So I preferred to teach you an easier technique. But bear in mind that concatenation is =>
BETTER <=
Concatenation
It allows you to do more things. How could you mix two variables, for instance? With a concatenation!
Code: PHP1
2
3
4
5
6 | <?php
$first_name = 'John ';
$name = 'Smith';
$complete_name = $first_name . $name;
?>
|
$complete_name will stand for "John Smith".
You will see how convenient it is. In addition, it is easy to do and to understand, isn't it? We tell PHP:
$complete_name stands for $first_name and $name
The "and" accounts for the concatenation's full stop.
We can also do a concatenation on the same variable. Twisted, but convenient again:
Code: PHP1
2
3
4 | <?php
$sentence = 'I am ';
$sentence = $phrase . 'a Newbie';
?>
|
At the end, the sentence will stand for "I am a Newbie".
Now, you're going to ask me: "Why making a concatenation on the same variable"? Well, sometimes you need to put a lot of text in a variable. Instead of writing everything on the same line, you start on the next line (just as I did) and you use a concatenation to combine the variable's content with the end of the sentence.
Clever bit! When making a concatenation on the same variable, you can also write $sentence .= 'a Newbie';
This shortcut spares you the bother of writing $sentence twice on the same line.
We'll stop here with concatenation, there's nothing so difficult about it
Apostrophes
I guess that apostrophes (which I will now use instead of inverted commas) might disturb you a bit. Because I want you to understand
why I'd rather use them, I'll give you some clues:
- First and most important point: contrary to inverted commas, if a variable is between apostrophes, we do not display its content.
In other words, if we have a variable $var = 'To eat':
- echo "$var; will display To eat
- echo '$var; will display $var
It is not a problem anymore, now that we have concatenation. As we will never write any variables between apostrophes again, there is no possibility to see $var displayed.
So to display the content of $var we will write: echo 'Text' . $var . 'End of text;
- Using apostrophes will spare you from typing backslashes \ before your inverted commas. This is really useful because as HTML requires to write a lot of inverted commas, it avoids writing loads of backslashes. For instance, in this code we avoided 4 backslashes:
echo '<img src="myimage.jpg" alt="This is an image" />';
- But now you are wondering how are we going to insert apostrophes? That's the other side of the coin. This time, we'll have to put backslashes before the apostrophes: echo 'He found it at his friend Paco\'s place';
In fact it is still more profitable to use apostrophes to mark off your text because in practice, the use of HTML with inverted commas is widespread compared to long literary texts with a great deal of apostrophes.
That's it, we're done
And remember: from now on, if I see anyone not using concatenation or still using inverted commas, I'll make mincemeat of him
Now we'll see a series of functions ready to use in PHP and working on character strings.
A character string is simply a variable that contains text.
All the functions that you are going to see are easy to use, as far as you know them when you need to
I will list the most useful ones and give you a quick explanation. If you want to know all the functions dealing with character strings, don't hesitate to check the PHP manual (don't focus on its austerity, it's very efficient!).
addslashes
This function adds backslashes
\ in your string. What for? To avoid bugs in case your string contains inverted commas or apostrophes. You may not see how handy it comes yet, but remember this function does exist because you will need it later for sure.
We use it this way:
Code: PHP1
2
3 | <?php
$new_variable = addslashes($previous_variable);
?>
|
If we take this string as an example:
Elvis Presley was the "King", there's no doubt about that!
After using addslashes, it will become:
Elvis Presley was the \"King\", there\'s no doubt about that!
You can see that it adds backslashes just before the apostrophes and inverted commas.
stripslashes
I'll be fast on this one, it's the exact opposite of addslashes. It removes backslashes from your string.
Code: PHP1
2
3 | <?php
$new_variable = stripslashes($previous_variable);
?>
|
If we take the string:
Elvis Presley was the \"King\", there\'s no doubt about that!
After using stripslashes, it will turn back to:
Elvis Presley was the "King", there's no doubt about that!
htmlspecialchars
You have already seen this one, if I'm not mistaken
It converts a string's HTML characters into a code that has no chance of being executed. Very useful if you make a minichat and want to prevent your guests from using HTML!
Code: PHP1
2
3
4
5
6 | <?php
$variable_html = '<em>This is a variable that contains HTML</em>';
$variable_without_html = htmlspecialchars($variable_html);
echo 'Before : ' . $variable_html . '<br />After : ' . $variable_without_html;
?>
|
I assume you didn't fail to notice the pretty concatenation
There are other similar functions that might be useful to you: htmlspecialchars blocks the most used HTML characters only (< > & " '), whereas strip_tags deletes the HTML tags straight out.
nl2br
Super-useful, we'll use it in the following chapter!
The nl2br function transforms all the "Enter" key pressed by your guest in HTML code "<br />" (which makes you start on the next line).
Indeed, as you may know it already, pressing the "Enter" key does not have any impact in HTML (it doesn't make you start on the next line). You can't imagine how lucky we are to have nl2br
Code: PHP1
2
3
4
5
6
7
8
9 | <?php
$my_variable = 'This is the first line.
This is the second line.
This is the third line.
OK we\'ll stop there...';
$my_variable = nl2br($my_variable);
echo $my_variable;
?>
|
Hang on a second! I just don't see what extraordinary things your code can do?!
Let's try without nl2br and you'll understand:
Code: PHP1
2
3
4
5
6
7
8 | <?php
$my_variable = 'This is the first line.
This is the second line.
This is the third line.
OK we\'ll stop there...';
echo $my_variable;
?>
|
As you can see, you don't start on the next line automatically without nl2br! I know...but it's not PHP's fault, it's just the way HTML is.
strlen
This function returns a character string's length, i.e the number of letters and figures it contains (spaces included). Example:
Code: PHP1
2
3
4
5
6
7 | <?php
$sentence = 'Hi Newbies! I am a sentence!';
$length = strlen($sentence);
echo 'The sentence below contains ' . $length . ' characters :<br />' . $sentence;
?>
|
You can count the characters if you want to, I guarantee there are 41 of them!
str_replace
str_replace replaces a character string by another. Example:
Code: PHP1
2
3
4
5 | <?php
$my_variable = str_replace('b', 'p', 'bim bam boum');
echo $my_variable;
?>
|
We need to indicate 3 parameters:
1. The string we are looking for. Here, we are looking for the letter "b" (we could have looked for a word as well).
2. The string with which we want to replace it. Here, we are putting "p" instead of "b".
3. The string in which we have to do the search.
Which gives us "pim pam poum"
str_shuffle
Just to have fun shuffling your string's characters randomly!
Code: PHP1
2
3
4
5
6 | <?php
$string = 'This string is going to be shuffled!';
$string = str_shuffle($string);
echo $string;
?>
|
strtolower
strtolower converts all the characters of a string in lowercase.
Code: PHP1
2
3
4
5
6 | <?php
$string = 'WHAT DO YOU MEAN I\'M SHOUTING???';
$string = strtolower($string);
echo $string;
?>
|
You should know there is another function called strtoupper that does exactly the same thing, but in the opposite way: lowercase => uppercase.
I can already see some of you staring wide-eyed

Don't worry, you're not seeing double!
It might look far-fetched at first glance. I, who didn't even know it existed, reached nirvana when I became aware of it
We'll start from a practical case.
I have 3 variables:$city, $country, $continent. I want to display one of these 3 variables' content according to another one's value ($display). Didn't I mention it was far-fetched?
If the value of $display is "city", then display the content of $city.
If the value of $display is "country", then display the content of $country.
If the value of $display is "continent", then display the content of $continent.
I assume you are able to write this code, aren't you? I think you would use conditions:
Code: PHP 1
2
3
4
5
6
7
8
9
10
11
12
13
14 | <?php
if ($display == 'city')
{
echo $city;
}
elseif ($display == 'country')
{
echo $country;
}
elseif ($display == 'continent')
{
echo $continent;
}
?>
|
Rubbish... It's heavy, repetitive, and quite often you are more likely to have a problem with 300 variables rather than 3. I'm not sure whether you'd like to stuff 300 "if"'s in your code
The answer? Ask PHP to display a variable's content according to another variable.
We will need to use a dollar followed by braces (
${}). In fact, we will write ${$display}.
$display will be replaced by its value (for instance "city"), which will enable PHP to understand that it is the variable "city"!
Since you are skeptical (which is a natural state after reading all the twisted atrocities I just came out with), here is a source code that works like the previous one:
Code: PHP 1
2
3
4
5
6
7
8
9
10 | <?php
$display = 'city'; // Modify the value of $display to see...
// We define the 3 variables we've talked about
$city = 'Glasgow';
$country = 'Scotland';
$continent = 'Europe';
echo ${$display}; // We display the variable whose name is "city" in our example
?>
|
I must admit that it's quite difficult to explain with words, and for once (just for once), I think it's easier to understand by reading the source code
So read this code again and again, soon you'll know how it works. Above all, make a few tests at home. For instance you can put $display = "country" to see what it does
We can go further. You can put the text that you want between the braces, just use a concatenation inside!
echo ${'mateo_' . $display};
Which will, in our example, display the content of the variable $mateo_city !
What we have to remember from this chapter is:
- That concatenation and apostrophes are nice, we must use them.
- The list of functions I made for you on character strings. It would be ideal to know them by heart (it's not that long) because you will be using them almost all the time!
The variable variables are a bit more specific. Just bear in mind that they exist, and if one day you need them, you'll go back to this chapter to know how to use them