Strings

PHP · Lesson 6 of 37 7 min read Updated

Most of what a website shows is text: names, addresses, messages, product titles. In PHP, a piece of text is called a string, and PHP has a large toolbox of functions for working with strings.

In this lesson you will learn the different ways to write strings, how to put variables inside them, the string functions you will use most, and how to handle Hindi and other non-English text correctly.

Single quotes and double quotes

You can write a string with single quotes '...' or double quotes "...". They are not the same:

  • Single quotes show the text almost exactly as written. Only \' (a quote) and \\ (a backslash) are special.
  • Double quotes replace variables with their values, which is called interpolation, and understand escape sequences such as \n (new line), \t (tab), \" and \$.
PHP
<?php
declare(strict_types=1);

$name = 'Isha';

echo 'Hello, $name\n';
echo "\n";
echo "Hello, $name\n";
echo "The \$name variable holds \"$name\"\n";
echo 'It\'s Isha\'s turn to bat', "\n";
Output
Hello, $name\n
Hello, Isha
The $name variable holds "Isha"
It's Isha's turn to bat

A simple rule: use single quotes for plain text, and double quotes when you want variables or \n inside.

Interpolation with curly braces

Inside double quotes, PHP reads a variable name for as long as it can. When the text right after a variable could be part of the name, or when you want an array item, wrap the expression in curly braces {...}:

PHP
<?php
declare(strict_types=1);

$item = 'samosa';
$student = ['name' => 'Kabir', 'class' => 10];

echo "Two {$item}s, please\n";
echo "{$student['name']} studies in class {$student['class']}.\n";
Output
Two samosas, please
Kabir studies in class 10.

Without braces, "Two $items" would look for a variable called $items, which does not exist. The braced form {$...} always works, so many developers use it for anything more than a plain variable.

Joining strings

The dot . joins (concatenates) strings. The .= operator adds text to the end of an existing string. Do not use + for strings: in PHP, + is only for numbers.

PHP
<?php
declare(strict_types=1);

$customer = 'Farhan';
$message = 'Dear ' . $customer . ',';
$message .= "\nYour parcel from Kochi has been shipped.";
$message .= "\nTrack it in the app.";

echo $message, "\n";
Output
Dear Farhan,
Your parcel from Kochi has been shipped.
Track it in the app.

Heredoc and nowdoc

For longer text over several lines, use a heredoc. It starts with <<< and a label of your choice, and ends with the same label on its own line. A heredoc works like a double-quoted string, so variables are replaced. A nowdoc puts the label in single quotes and works like a single-quoted string, with no replacement.

PHP
<?php
declare(strict_types=1);

$customer = 'Meera';
$orderId = 4521;
$total = 1299;

$email = <<<TEXT
    Hello $customer,
    Your order #$orderId is confirmed.
    Amount paid: ₹$total
    TEXT;
echo $email, "\n";

$template = <<<'TEXT'
    Dear $customer, thank you for shopping with us.
    TEXT;
echo $template, "\n";
Output
Hello Meera,
Your order #4521 is confirmed.
Amount paid: ₹1299
Dear $customer, thank you for shopping with us.

The closing label can be indented. PHP removes that same amount of indentation from every line, so you can keep your code neatly lined up.

Everyday string functions

PHP has a large set of string functions. These are the ones you will reach for most often:

FunctionWhat it doesExample result
strlen($s)Length in bytesstrlen('Pune') is 4
trim($s)Removes spaces at both ends' hi ' becomes 'hi'
strtolower($s), strtoupper($s)Change case'pune', 'PUNE'
ucfirst($s), ucwords($s)Capitalise first letter or each word'Priya Sharma'
str_replace($find, $replace, $s)Replace textSwap one word for another
substr($s, $start, $length)Cut out part of a stringsubstr('Jaipur', 0, 3) is 'Jai'
str_contains($s, $part)Does it contain the text?true or false
str_starts_with(), str_ends_with()Check the beginning or endtrue or false
sprintf($format, ...)Build a formatted string'0007' from 7
PHP
<?php
declare(strict_types=1);

$input = '  priya sharma  ';
$name = trim($input);

echo ucwords($name), "\n";
echo strtoupper($name), "\n";
echo str_replace('sharma', 'verma', $name), "\n";
echo substr($name, 0, 5), "\n";
var_dump(str_contains($name, 'sharma'));
var_dump(str_ends_with('marksheet.pdf', '.pdf'));

printf("Roll no: %04d, Marks: %.1f%%\n", 7, 86.456);
Output
Priya Sharma
PRIYA SHARMA
priya verma
priya
bool(true)
bool(true)
Roll no: 0007, Marks: 86.5%

printf() prints a formatted string and sprintf() returns it instead. In the format, %04d means "a whole number, at least 4 digits, padded with zeros", %.1f means "a decimal number with 1 digit after the point" and %% prints a percent sign.

Strings are case-sensitive in all these functions: str_contains('Pune', 'pune') is false. Convert both sides with strtolower() first when case should not matter.

Hindi and other UTF-8 text

PHP strings are sequences of bytes. English letters take one byte each in UTF-8, the standard text encoding of the web, but Hindi letters take three bytes each, and symbols like ₹ take three too. Functions such as strlen() and substr() count bytes, so they give wrong answers for Hindi text and can even cut a letter in half.

The mbstring extension (multibyte string) has versions of these functions that count real characters. Their names start with mb_. The extension is switched on in XAMPP, Laragon and most hosting; if PHP says mb_strlen() is undefined, enable extension=mbstring in php.ini.

PHP
<?php
declare(strict_types=1);

$greeting = 'नमस्ते';

echo strlen($greeting), "\n";
echo mb_strlen($greeting), "\n";
echo mb_substr($greeting, 0, 2), "\n";

echo strtoupper('café'), "\n";
echo mb_strtoupper('café'), "\n";
Output
18
6
नम
CAFé
CAFÉ

mb_strlen() counts 6 characters because Hindi vowel signs (matras) and the halant are stored as separate characters. Still, 6 is the right answer for most tasks, such as limiting a name to 50 characters, and 18 never is.

Rules for text that might not be English, which on an Indian website is almost all text:

  • Use mb_strlen(), mb_substr(), mb_strtoupper(), mb_strtolower() and mb_str_split().
  • Save your .php files as UTF-8 (VS Code does this by default).
  • Never use strrev() or str_split() on Hindi text; they work on bytes and produce broken characters.

Common mistakes

  • Checking strpos() as true or false. strpos('report.pdf', 'report') returns 0 (the position), and 0 is falsy. Use str_contains() for "does it contain?", or compare with !== false.
  • Expecting variables to work in single quotes. 'Hello $name' prints the dollar sign and the name literally.
  • Using + to join strings. Use . instead. 'a' + 'b' throws a TypeError.
  • Using strlen() to limit Hindi input. Use mb_strlen() so a 10-character name is not rejected as 30 bytes long.

Key points

  • Single quotes keep text as written; double quotes replace variables and understand \n.
  • Use {$...} inside double quotes for array items and to separate a variable from the text after it.
  • . joins strings and .= appends; + is only for numbers.
  • Heredoc (<<<TEXT) is a multi-line double-quoted string; nowdoc (<<<'TEXT') is a multi-line single-quoted string.
  • str_contains(), str_starts_with() and str_ends_with() give clear true-or-false answers.
  • Use mb_* functions for Hindi and any other UTF-8 text.

Exercise

A user signs up with the name ' ananya iyer ' and the city 'कोच्चि'. Write a script that trims the name and capitalises each word, prints a welcome message using a heredoc, and prints the number of characters in the city name using the correct function. Finally, print true or false (with var_dump()) for whether the cleaned name contains 'Iyer'.

Show solution
PHP
<?php
declare(strict_types=1);

$name = ucwords(trim('  ananya iyer '));
$city = 'कोच्चि';
$cityLength = mb_strlen($city);

echo <<<TEXT
    Welcome, $name!
    Your city name has $cityLength characters.
    TEXT;
echo "\n";

var_dump(str_contains($name, 'Iyer'));
Output
Welcome, Ananya Iyer!
Your city name has 6 characters.
bool(true)

trim() removes the spaces before ucwords() capitalises each word. mb_strlen() counts characters rather than bytes, so the Hindi city name gives a sensible count.

Quick Quiz

1. What does echo 'Total: $sum'; print?

2. Which line correctly prints a value from the array $user inside a string?

3. strlen('नमस्ते') returns 18. Which function returns the character count instead?

4. Why is if (strpos($file, 'report')) a bug when $file is 'report.pdf'?

Learn PHP with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call