Lesson 4 of 12

PHP Strings

Most of what a website shows is text: names, addresses, product titles, messages. In PHP, text is stored as a string. This lesson covers the different ways to write PHP strings, how to join them, and the built-in functions you will reach for again and again. It builds on PHP Data Types.

Single quotes vs double quotes

You can wrap a string in single quotes '...' or double quotes "...". The difference matters:

  • Single quotes keep the text exactly as written. Variables and most escape sequences are not processed. Only \' (a quote) and \\ (a backslash) are special.
  • Double quotes replace variables with their values and understand escape sequences such as \n (new line) and \t (tab).

A simple rule for PHP strings: use single quotes for fixed text, and double quotes when you want to insert variables. For array items or object properties inside double quotes, wrap the expression in curly braces, like "{$order['id']}", so PHP knows exactly where the variable ends.

<?php
$firstName = "Lakshmi";
$lastName  = "Narayanan";
$order     = ['id' => 1042, 'city' => 'Tiruchirappalli'];

echo 'Hello $firstName\n', "\n";
echo "Hello $firstName\n";
echo "Order {$order['id']} ships to {$order['city']}.\n";

$fullName = $firstName . " " . $lastName;
$fullName .= " (customer)";
echo $fullName;
Output
Hello $firstName\n
Hello Lakshmi
Order 1042 ships to Tiruchirappalli.
Lakshmi Narayanan (customer)

The dot . is the concatenation operator: it joins two strings. The combined form .= adds text to the end of an existing variable, which is handy when you build up a message line by line.

Heredoc for longer text

When you need several lines, such as an email body or a block of HTML, a heredoc is easier to read than many joined strings. It starts with <<< and an identifier, and ends with the same identifier on its own line. A heredoc behaves like a double-quoted string, so variables are replaced. Its sibling, the nowdoc (identifier in single quotes, <<<'TXT'), behaves like a single-quoted string.

<?php
$guest  = "Farhan";
$nights = 2;
$hotel  = "Sea Breeze Stay";

$message = <<<TEXT
    Dear $guest,
    Your booking at $hotel is confirmed for $nights nights.
    See you in Puducherry!
    TEXT;

echo $message;
Output
Dear Farhan,
Your booking at Sea Breeze Stay is confirmed for 2 nights.
See you in Puducherry!

Since PHP 7.3, the closing identifier may be indented, and that indentation is removed from every line. That is why the output starts at the left edge.

Everyday string functions

PHP ships with a large library of string functions. These are the ones beginners use most:

FunctionWhat it does
strlen($s)Length in bytes.
mb_strlen($s)Length in characters; correct for ₹, emoji, accented letters and Indian scripts.
strtoupper() / strtolower()Change case (use mb_strtoupper() for non-English text).
ucfirst() / ucwords()Capitalise the first letter / the first letter of each word.
trim($s)Remove spaces and new lines from both ends – essential for form input.
str_contains($s, $part)Does the string contain this text? Returns true or false (PHP 8+).
str_starts_with() / str_ends_with()Check the beginning or end of a string (PHP 8+).
str_replace($find, $replace, $s)Replace every occurrence of some text.
substr($s, $start, $length)Take part of a string (use mb_substr() for multibyte text).
explode($sep, $s) / implode($sep, $arr)Split a string into an array / join an array into a string.
sprintf() / number_format()Build formatted strings and numbers.
<?php
$input = "   idli, dosa, vada   ";
$clean = trim($input);

echo strtoupper($clean), "\n";
echo ucwords($clean), "\n";
var_dump(str_contains($clean, "dosa"));
var_dump(str_starts_with($clean, "vada"));
echo str_replace("vada", "pongal", $clean), "\n";
echo substr($clean, 0, 4), "\n";

$items = explode(", ", $clean);
echo count($items), " items: ", implode(" | ", $items), "\n";

$price = "₹1,500";
echo strlen($price), " bytes, ", mb_strlen($price), " characters\n";

echo sprintf("%s costs Rs. %.2f", "Masala dosa", 85), "\n";
echo number_format(1250000.5, 2);
Output
IDLI, DOSA, VADA
Idli, Dosa, Vada
bool(true)
bool(false)
idli, dosa, pongal
idli
3 items: idli | dosa | vada
8 bytes, 6 characters
Masala dosa costs Rs. 85.00
1,250,000.50

Two details stand out. First, strlen() counts bytes. The rupee sign ₹ takes three bytes in UTF-8, so "₹1,500" is 8 bytes but only 6 characters. Use the mb_ functions whenever text may contain more than plain English letters. With Indian scripts there is one more subtlety: a Tamil or Hindi letter with a vowel sign is stored as two Unicode characters, so mb_strlen("சென்னை") returns 6 even though a reader sees three letters. When you need what the reader sees, the intl extension offers grapheme_strlen(), which returns 3. Second, sprintf() uses placeholders: %s for a string, %d for an integer and %.2f for a float with two decimals.

Tip: number_format() groups digits in thousands (1,250,000.50). For the Indian lakh/crore style (12,50,000.50), use the NumberFormatter class from the intl extension with the en_IN locale.

Comparing PHP strings

Use === to check whether two strings are exactly equal. Comparison is case-sensitive, so "Goa" === "goa" is false. To ignore case, compare lowercase versions or use strcasecmp(), which returns 0 when the strings match.

Watch out: Never print user input straight into a web page. Text like <script> would run as code in other people’s browsers. Escape it with htmlspecialchars(), which you will use in PHP Forms.

Next, PHP Operators covers arithmetic, comparison and the null coalescing operator.

Further reading

Key takeaways

  • Single quotes keep text literal; double quotes and heredoc replace variables and escape sequences.
  • Join strings with . and append with .=; use {$array['key']} inside double quotes.
  • trim(), str_contains(), str_replace(), explode() and sprintf() cover most daily tasks.
  • Use mb_ functions for text in Indian languages or with emoji, because strlen() counts bytes.
  • Escape user text with htmlspecialchars() before printing it in HTML.

Quick quiz

Check what you learned – pick an answer.

1. If $item = "chai", what does echo 'Order: $item'; print?

2. Which function returns true if "Kochi Metro" contains "Metro"?

3. Why might strlen("மதுரை") return a larger number than you expect?

Practice exercise

A user typed " priya SHARMA " into a name field. Clean it up so it prints as Welcome, Priya Sharma!.

Show a hint

Combine trim(), strtolower() and ucwords(), then build the message with a double-quoted string.

Show the solution
<?php
$raw = "  priya SHARMA  ";
$name = ucwords(strtolower(trim($raw)));

echo "Welcome, $name!";

Progress is saved in this browser only.