Curriculum
This tutorial will teach you about PHP strings and how to manipulate them effectively.
A string in PHP is a sequence of characters. PHP allows you to define a literal string in four ways: single-quoted, double-quoted, heredoc syntax, and nowdoc syntax. The single-quoted and double-quoted strings are the focus of this tutorial.
To define a string, enclose the text in single quotes as shown:
<?php $title = 'PHP string is awesome';
You can also use double quotes:
<?php $title = "PHP string is awesome";
You cannot, however, begin a string with a single quote and end it with a double quote, or vice versa. The quotations must all be consistent.
Assume you have a variable named $name.
<?php $name = 'John';
And you’d like to display the following message:
Hello John
To do so, use the concatenate operator (.) to join two strings:
<?php $name = 'John'; echo 'Hello ' . $name;
However, if you use a double-quoted string, you can insert the $name variable as follows:
<?php $name = 'John'; echo "Hello $name";
When PHP evaluates a double-quoted string, it replaces the value of any variables placed within the string. In PHP, this is known as variable interpolation.
An alternative syntax is to enclose the variable in curly braces, as shown below:
<?php $name = 'John'; echo "Hello {$name}";
The result is the same.
It’s worth noting that PHP does not substitute the value of variables in single-quoted strings, such as:
<?php $name = 'John'; echo 'Hello {$name}';
The result will be as follows:
In addition to substituting variables, double-quoted strings accept special characters, such as n, r, and t, by escaping them.
When you don’t use variable interpolation, it’s a good idea to use single-quoted strings because PHP doesn’t have to parse and evaluate them like it does with double-quoted strings.
The index of a string is zero-based. This indicates that the first character has an index of 0. The index for the second character is one, and so on.
The following syntax is used to access a single character in a string at a specific position:
$str[index]
<?php $title = 'PHP string is awesome'; echo $title[0];
Output
P
To determine the length of a string, use the built-in function strlen(), as shown below:
<?php $title = 'PHP string is awesome'; echo strlen($title);