A string in PHP is a sequence of characters, such as “Hello, world!”.
Example:
echo "Hello"; echo 'Hello';
Differences between Double and Single Quotes
In PHP, strings can be enclosed in either double or single quotes. However, there are notable differences between the two:
- Double Quotes: Process special characters and allow for variable interpolation.
- Single Quotes: Do not process special characters, treating them as plain text.
Double or Single Quotes?
You can choose either double or single quotes, but understanding the differences can help you decide which to use.
Example with Double Quotes:
Double-quoted strings process special characters and allow variable interpolation.
$name = "Harley"; echo "Welcome, $name!";
Example with Single Quotes:
Single-quoted strings treat special characters as plain text and do not process variable interpolation.
$name = "Harley"; echo 'Welcome, $name!';
String Length
The strlen()
function returns the length of a string.
Example:
echo strlen("Motorcycle brands!");
Word Count
The str_word_count()
function counts the number of words in a string.
Example:
echo str_word_count("Hello motorcycle world!");
Search for Text Within a String
The strpos()
function searches for specific text within a string and returns the character position of the first match. If no match is found, it returns FALSE
.
Example:
echo strpos("Welcome to the motorcycle world!", "motorcycle");