#native_company# #native_desc#
#native_cta#

Strings & Text in PHP – The ABCs of PHP Part 5

By PHP Builder Staff
on April 15, 2009

In the last part of this series we looked at what a variable
was in general. Today we’ll be covering strings and text.
We’ll look at the contents those variables would typically
hold.
What is a string?
Put simply a string is any sequence of alpha/numeric or
punctuation characters enclosed by either a set of “”
parentheses or a set of ” parentheses.
Strings are generally used to hold data that we as humans
may write down in a sentence or read in a document such as
this one, and generally we would not normally perform
mathematical calculations on a string. This is not to say
however that a string cannot hold a number value, it can.
Under normal circumstances however, you would not unless
that number was purely for display.
You’ll notice also that there are 2 sets of parentheses used
to enclose strings mentioned above, each set operates
differently to the other.
Using ” parentheses
When you enclose a PHP string using ” (Otherwise know as
single quotation marks) exactly what you put in the string
is displayed. This means that no embedded variables are
translated and no special sequences such as carriage returns
are obeyed.
Let me show you an example:
<?php

  $variable = 'Hello world';

  Print 'Here is some text [$variable]';

?>
When this is run from the command line the following will be output:
Here is some text [$variable]
Given what we’ve discussed so far, you might think that this
is to be expected, and in a way you would be right, however
things are rather different when using the alternate
double quote parentheses.
Using “” parentheses
So what’s so different about using “” (Otherwise known as double quotation marks), well when we use “” PHP actually interprets the contents of the string. In the case of embedded variable names, these are substituted for the actual contents of the variable, in the case of special escape sequences these are interpreted and replaced with different values as required (More on those in just a moment).
Using the same example as before, let’s rewrite it with double quotes instead of single quotes.
<?php

  $variable = "Hello world";

  print "Here is some text [$variable]";

?>
This will now output:
Here is some text [Hello world]
PHP’s ability to substitute variables directly in a sctring
like that is one of it’s strongest features, and sometimes a
source of frustration to the beginner.
Many PHP beginners assume that because they can insert
variables using double quotes, they can also do the same
using PHP’s built in functions, unfortunately this will not
work as expected. EG:
A user trying to use:
<?php

  Print "Todays date is date('r')";

?>
May rightfully assume that the result would be:
Todays date is Wed, 25 Mar 2009 13:32:21 +0000
When in actual fact the result will be:
Todays date is date('r')

1
|
2
|
3
|
4