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:
Output: PHP script
<?php
echo "Hello";
echo "<br>";
echo 'Hello';
?>
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:
Output: PHP script
<?php
$x = "John";
echo "Hello $x";
?>
Single quoted string
This is the same code with single quotes, and the output now shows the name $x itself:
Output: PHP script
<?php
$x = "John";
echo 'Hello $x';
?>
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:
Output: PHP script
<?php
echo strlen("Hello world!");
?>
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:
Output: PHP script
<?php
echo str_word_count("Hello world!");
?>
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:
Output: PHP script
<?php
echo strpos("Hello world!", "world");
?>