Skip to main content

PHP Strings

Think of a string as a piece of text: a series of characters such as "Hello world!". To show PHP where the text begins and ends, you wrap it in quotes, and either double or single quotes will do.

Double or single quotes

Both kinds of quotes produce a valid string, as this script shows by printing the same word twice:

Prompt
Write a PHP script that uses echo to display "Hello" using double quotes and then echo to display 'Hello' using single quotes, each on a separate line.
Output: PHP script

Double or Single Quotes?

Your choice of quotes changes how PHP reads what is inside them. With double quotes, PHP looks for variables in the text and swaps each name for its value, which is known as variable interpolation. With single quotes, nothing is swapped: the text, including any variable name, is printed exactly as you typed it.

Double quoted string

Here $x sits inside double quotes, so its value appears in the output:

Prompt
Write a PHP script that creates a variable $x set to "John". Use echo with a double-quoted string "Hello $x" to show how the variable is interpolated.
Output: PHP script

Single quoted string

This is the same code with single quotes, and the output now shows the name $x itself:

Prompt
Write a PHP script that creates a variable $x set to "John". Use echo with a single-quoted string 'Hello $x' to show that the variable name is displayed literally.
Output: PHP script

String Length

To find out how many characters a string holds, call strlen(). The number it gives back is the string's length.

strlen() example

"Hello world!" is 12 characters long, counting the space and the exclamation mark:

Prompt
Write a PHP script that uses echo and strlen() to display the length of the string "Hello world!".
Output: PHP script

Word Count

When you need words rather than characters, str_word_count() tells you how many words a string contains.

str_word_count() example

"Hello world!" contains two words:

Prompt
Write a PHP script that uses echo and str_word_count() to display the number of words in the string "Hello world!".
Output: PHP script

Search For Text Within a String

Use strpos() to look for a piece of text inside a string. When it finds the text, you get back the character position where the first match starts. When it finds nothing, you get FALSE.

strpos() example

Here we look for "world" in "Hello world!". It starts at position 6, because counting begins at 0:

Prompt
Write a PHP script that uses echo and strpos() to search for the text "world" in the string "Hello world!" and display the position.
Output: PHP script