PHP Strings

Strings can be saved as a variable, or used immediately as a function.

If you plan on using a string immediately as a function, you could simply use it right away in an echo:

echo "My favorite website is";

This bit of code would display:

My favorite website is

If you plan to use a string more than once, you would most likely save it as a variable:

$thestring = "My favorite website is";

echo $thestring;

This bit of code would display the same thing:

My favorite website is

Notice, however, that we created a variable and named it $thestring. We can then use that variable wherever we want later in the code by using $thestring.

Using Single Quotes With Strings

It is important to note that anytime you are using a single quote within your strings, you must escape it using a backslash (\).


$thestring = " It\'s my favorite website!";

For more information, see PHP Syntax.

Joining Strings

You can join multiple strings together by using the concentration operator, which is a period (.).

$tagline="Where Fortunes Are Made";
echo $thestring . $tagline;

This bit of code would display:
Where Fortunes Are Made

Notice that we created a new line using “\n”. We then used the concentration operator (.) to join the two strings together.

See also the strlen() and strpos() functions.