PHP Strings

Probably the most used data type in any PHP script is the string. Fundamentally, a PHP string is just a sequence of characters. However, there is more than one way to define a string, and how you define it turns out to be very important.

The first way to define a string, and the way I’ve consistently been defining them in the videos up until this point, is inside single-quotes. And with single-quotes, whatever you type inbetween your quotes is the exact value of the expression, with one exception. You can escape apostrophes inside single-quotes by using a backslash.

$quoted = ‘I don\’t break’; //$quoted gets value “I don’t break”

Double-quoted strings, on the other hand, are far more interesting in PHP. With double-quoted strings, you can embed variables that will form the contents of the string based on their value when the string’s expression is evaluated. So for instance:

$color = ‘green’;
$useVar = “I see a $color truck”; //$useVar now says ‘I see a green truck’
echo $useVar;

Now, if $color wasn’t set before the string expression was evaluated, your message would just be ‘I see a  truck’.

Sometimes, you want a double-quoted string to contain a $ without getting evaluated. PHP knows that if a $ is by itself, or if it’s followed by numbers rather than letters, to leave it as a $ when evaluating the string. However, if you want to see the literal string ‘$color’ inside your double-quoted string, you just need to escape your $ with a backslash, like this:

$useVar = “I see a \$color truck”;

Escaping is particularly important with double-quoted strings. To get a literal double-quote, just place a back-slash in front of it. Same to get a literal backslash.

Something else you can do, however, is use the backslash to get a newline, carriage return, or a horizontal tab.

In order, those are:

“\n”;
“\r”;
“\t”;

This is especially useful when you’re sending your output to a file or in an email, and you need to end your lines with the appropriate line-termination character. When outputting your contents to the web of course, your audience will be much more concerned about whether you use the <br> tag, since new-lines don’t generally show up. Although, even when outputting HTML, having new-lines in places where they make sense can make your HTML much easier for a human to read.

If your double-quoted string needs to have a variable show up right in front of characters, you can use braces to let the PHP engine differentiate between the variable and the string content. For instance:

$type = ‘dodge’;
$message = “Let’s go play {$type}ball tonight!”;
echo $message;

Without the braces, PHP would look for a variable name $typeball, and on failing to find it, would replace it in with the empty string.

With double-quoted strings, you can also insert values from arrays, like so:

$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the $var1[two] milkshake”;

Notice, I don’t have to use single quotes around the key when I’m in the string. As a matter of fact, if I use the single quotes around my array key, I’ll get a parse error. However, if I use braces, I can stick the single quotes in.

$var1 = array(‘one’=>’orange’, ‘two’=>’banana’);
$message = “I am hungry for the {$var1[‘two’]} milkshake”;

Now a point I want to make about single quotes versus double quotes, and it should be pretty obvious. Since double-quotes require an extra step from the interpreter before it can evaluate them, there’s a slight performance penalty. If all you need are literal strings without variables or special characters, use single-quoted strings. They’re just a little bit faster. It’s not a big deal, but it’s good practice to pick the faster option when you can.

Moving on, there are 2 other ways to define strings. They’re called NOWDOC and HEREDOC. They look pretty similar, and they’re handy when you need to put a long block of text into a variable, but they can get you into trouble if you aren’t careful.

First, NOWDOC. NOWDOC begins with three ‘less than’ signs together, followed by an upper-case, single-quoted string. You place any text you want after that opening, and then you end it with the original identifier, without any quotes. Here’s an example:

$color = ‘green’;
$myNowdocString = <<<‘MYNOWDOC’
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYNOWDOC;

The most important warning here is that you must have a newline right after the opening tag, and a newline right before the closing tag. And on the line with the closing tag, there can be no other characters or spaces save for the closing semi-colon. If PHP doesn’t find the exact closing tag it’s looking for, it’ll keep going down your script until it reaches the end, and will throw an error referencing the last line of your file.

What the NOWDOC syntax basically does is act like one single line in your PHP code, but lets you split it across as many lines as you need.

As with single-quotes, your text inside your NOWDOC will be interpreted exactly as it appears, with no need to escape anything.

It should be noted, that NOWDOC was introduced in PHP 5.3. Earlier versions don’t support it.

The last way to define a string is with HEREDOC syntax. And HEREDOC is to NOWDOC what double-quoted strings are to single-quoted strings. Since HEREDOC has been around longer, you can define it by using an opening tag with no quotes. But, since PHP 5.3 and NOWDOC syntax have arrived, the PHP engineers have driven home the single-quoted/double-quoted string parallel pretty hard by enabling you to define your opening tag as a double-quoted string, like so:

$color = ‘green’;
$myHeredocString = <<<“MYHEREDOC”
This short line of text is standing in for a longer line of text.<br>
I see a $color truck.
MYHEREDOC;

Since it’s analogous to a double-quoted string, that means you can embed variables and special characters in it, with all the same rules that apply to double-quoted strings. Obviously one of the main advantages to NOWDOC and HEREDOC over quoted strings is that there’s no need to escape quotes, and blocks of text can be easier to read in many cases.

When you need to combine strings together, you use a period. In PHP terms, the period is referred to in this case as the “string concatenation operator”. If you stick it in the middle of two string, or a string and something that can be converted to a string, the entire expression takes on the value of the first string joined to the second.

$color = ‘green’;
$joinedString = ‘I don\’t need any variables’ . “, but I see a $color truck.”;

And it’s not something you see everyday, but concatenation works on HEREDOC and NOWDOC strings as well. Just remember to have the period on a different line from your string ending tag.

Lastly, I want to point out that you can combine concatenation and assignment into one step. Suppose you have a variable named $string1 and you need to append some other string to the end of it. Well, you could do:

$string = $string . ‘ Now make it longer!’;

But you could get the exact same result by doing this:

$string .= ‘ Now make it longer!’;

PHP also supports a number of special functions for working with your strings, and that’s going to be the topic of a later video. In the meantime, you should now have all the tools you need to start using strings effectively in your own scripts.

February 08 2010 11:51 pm | Basics and PHP Programming Basics and PHP tutorial scripts

Comments are closed.