Silly Strings
Posted on 24. Feb, 2010 by admin in Basics
We only scratched the surface of what we can do with strings. So far we have only added text to them, and printed them out with echo. Before we move on we must examine this concept more closely to be successful in PHP. The first item we need to go over is the concatenation operator. This is just a technical term for combining strings that will come in handy later.
Let’s say you have two variables that you want to combine. The first is someone’s full name, and the second is someone’s last name. You, the developer, want to simply combine the two to retrieve the user’s full name. We do this with a concatenation operator. As you remember, before we used operators to add, subtract, multiply, etc. numbers. With a concatenation operator we are adding two or more strings together. In code this is done by adding a period in-between two string literals (the block of text inside quotes is called a string literal) or variables. To create the full name our code would look something like this:
<?php //Name Varibles $firstname = "John"; $lastname = "Doe"; //Combine Them $fullname = $firstname . $lastname; echo "His fullname is " . $fullname; ?>
See how we can combine two string variables by putting a period in-between? As you can also see from the script we can do it with other statements, such as echo.
With the echo statement we have only been able to print text without much formatting. If you have played around with the echo function you have probably also found that some characters, such as quotes, don’t work. A jumble of words or errors will not help us much so that is why they made escape characters.
<?php echo "First line\nSecond line"; echo "\t\"This is tabbed over and in quotes\""; ?>
Output(Only in Plain Text):
First line
Second line “This is tabbed over and in quotes”
A list of all the escape characters you need to know are below:
- Newline – \n
- Tab – \t
- Single Quote – \’
- Double Quote – \”
- Dollar Sign – \$
- Backslash – \\
You need to know all of the above escape characters. Using double quotes, a dollar sign, or any of the other characters in a regular string might cause your code to break or work incorrectly. You must use escape characters to print the above characters.
Strings are an important concept, so let’s try a little trail an error. Try to print out some of the statements below:
Q: Combine and print $string1 = “Hello ” and $string2 = “World”
Q: Print out “The apple is $1.25″
Q: Print out “This is a “test” of quotes”
Q: Print out “C:\php\index.php”
I hope this give you a little start on how versatile strings can be, and what we can do with them. Hold on because we are not done with strings yet!

