Blake O'Hare .com

PHP Tutorial Part 4 - Quick String Overview

"String" is just a fancy name for text. HTML code is just one big string. So this topic is kinda important.

Variables can hold strings also. A string is designated by text surrounded by quotation marks. We've been using strings this whole time in our examples because the echo statement is using them.

<html><body>
<?
  for ($x = 1; $x < 100; $x = $x + 1)
  {
    echo "<p>Meow!</p>";
  }
?>
</body></html>

"<p>Meow!</p>" is a string. Which means we could have written this script like this...

<html><body>
<?
  $fluffy = "Meow!";
  for ($x = 1; $x < 100; $x = $x + 1)
  {
    echo "<p>";
    echo $fluffy;
    echo "</p>";
  }
?>
</body></html>

This code does the same thing. But since we have the "Meow!" text stored in a variable called fluffy, we can make changes to it in the loop so the text changes each time to make things more interesting...

The Period Joins Strings Together

<html><body>
<?
  $fluffy = "Meow!";
  for ($x = 1; $x < 100; $x = $x + 1)
  {
    echo "<p>";
    echo $fluffy;
    echo "</p>";
    $fluffy = $fluffy."!";
  }
?>
</body></html>

The period operator adds items to a string. In this case, we are adding another ! to the end of the Meow string EACH TIME we go through this loop. When we run this, we should see something like this...

Meow!
Meow!!
Meow!!!
Meow!!!!
Meow!!!!!
Meow!!!!!!
Meow!!!!!!!
Meow!!!!!!!!
Meow!!!!!!!!!
...you get the idea

You can even use the period multiple times in the same line.

<?
  echo "This "."is "."a "."test!";
?>

Produces...
This is a test!


Using Single Quotes Instead of Double Quotes

Strings can also be designated by single quotes (apostrophes)

$foo = 'This is a string, too!';

This is convenient when you actually want to include a " inside your string. Quotes beginning with ' must always end with ' and quotes beginning with " must always end with ". No mixing and matching.

Next: Arrays
Back to Tutorial Overview