TOC

The community is working on translating this tutorial into Turkish, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Data types:

Working with strings

A string is a set of characters. In PHP, you may consider it to be an array of characters, because you may access a certain character in the string based on the zero-based index of it, just like with an array. In this chapter of the tutorial, we will work a bit with strings in a variety of ways, to show you the possibilities.

Defining strings

Defining strings in PHP is really easy. Simply wrap a piece of text with either single or double quotes, and you have a string. Like this:

<?php
$var = "A string";
echo $var;
?>

Or you can use a string directly for output, without defining it as a variable first:

<?php
echo "A string";
?>

As mentioned, you can use single quotes as well:

<?php
echo 'A string';
?>

Actually, there is a difference between using single and double quoted strings. Double quoted strings are parsed by PHP for variables and special escape sequences, allowing you to use variables inside of the string it self. Try running this example:

<?php
$message = "Hello, world!";

echo "The message variable contains the value $message<br /><br />";
echo 'The message variable contains the value $message';
?>

As you will see from the output, the first line outputs the value of the variable, while the second one simply outputs it as if it were just another piece of text. You may wish to use this feature of the double quoted strings, or you may wish to use concatenation, as described in the next section. The latter offers better performance, and some people believe it to be prettier code.

Escaping strings

So, what do you do when you wish to use a double quote inside of a double quoted string? You escape it, using the backslash character, like this:

<?php
echo "Is this a so-called \"test\" or not?";
?>

But, what if you need to use a \ character, for instance at the end of the string? Oh well, you escape that as well, like this:

<?php
echo "The last character is a backslash\\";
?>

Concatenating strings

The process of combining two or more strings is called concatenation. In PHP, it's done using the dot operator, like this:

<?php
$newString = $string1 . $string2;
?>

You may have more than two strings, and you may combine variables with quoted text, like this, where we combine the first and the last name of a person and put a space in between:

<?php
$name = $firstName . " " . $lastName;
?>

In the next chapter, we will work some more with strings, showing you various useful string related functions.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!