PHP Strings

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Basics

What You’ll Learn

Strings hold almost every piece of text in PHP—user names, product labels, HTML snippets, and CSV data. This guide teaches how to create strings, join them, pick the right quotes, and use essential built-in helpers.

01

String Basics

Text in PHP.

02

Quote Types

Single vs double.

03

Concatenation

Join with .

04

Common Helpers

strlen, trim, case.

05

Split & Join

explode / implode.

06

UTF-8 Encoding

International text.

Definition and Usage

In PHP, a string is a sequence of bytes representing text. Strings store everything from a single character to an entire HTML document. You assign them to variables, pass them to functions, and output them with echo.

PHP also provides many built-in helpers for searching, replacing, escaping, splitting, and encoding text. Before using those, learn the basics: how to write strings, when to use each quote style, and how to combine pieces with the concatenation operator (.).

💡
Beginner Tip

Use UTF-8 encoding in your PHP files and HTML pages so international characters (accents, emoji, non-Latin scripts) display correctly. Save .php files as UTF-8 and set <meta charset="UTF-8"> in HTML output.

📝 Syntax

PHP offers several ways to create strings:

PHP
$single  = 'Hello, PHP!';           // single quotes
$double  = "Hello, $name!";          // double quotes (variables expand)
$joined  = $first . ' ' . $last;     // concatenation
$length  = strlen($text);            // built-in helper

Quote Styles

  • Single quotes ('...') — mostly literal text; fast when you do not need variables inside.
  • Double quotes ("...") — expand $variables and escape sequences like \n.
  • Heredoc / Nowdoc — multi-line strings; heredoc expands variables, nowdoc does not (like single quotes).

Common Built-in Helpers

PHP helpers are global functions—the string is usually the first argument:

strlen($text)
strtoupper($text)
explode(",", $csvLine)
htmlspecialchars($userInput, ENT_QUOTES, "UTF-8")

⚡ Quick Reference

Create
$s = "Hello, PHP!";

Double-quoted string

Concatenate
$full = $a . " " . $b;

Dot operator

Length
strlen($text)

Byte length

Safe HTML
htmlspecialchars($x, ENT_QUOTES, "UTF-8")

Escape output

Examples Gallery

Work through these five examples from basic string creation to split-and-join patterns used in real PHP apps.

📚 Getting Started

Create your first strings and display them with echo.

Example 1 — Create and Display Strings

Assign text to variables and output it—the foundation of every PHP script.

PHP
<?php
$lang = "PHP";
$version = 8;

echo "Language: $lang\n";
echo 'Version: ', $version, "\n";
echo "Ready to learn strings!\n";
?>

How It Works

Double quotes expand $lang; commas in echo join literals and variables without extra concatenation. Numbers convert to strings automatically when echoed.

Example 2 — Single Quotes vs Double Quotes

See how variable expansion differs between quote styles.

PHP
<?php
$word = "World";

echo "Double: Hello, $word!\n";
echo 'Single: Hello, $word!\n';
echo "Newline: Line 1\nLine 2\n";
echo 'Newline: Line 1\nLine 2\n';
?>

How It Works

Double quotes interpret $variables and \n. Single quotes treat almost everything literally—ideal for file paths, regex patterns, and SQL fragments where $ should not expand.

📈 Practical Patterns

Concatenation, transformation, and list handling.

Example 3 — Concatenation with the Dot Operator

Build messages by joining strings and variables with . and .=.

PHP
<?php
$first = "Hello";
$last  = "PHP";

$greeting = $first . ", " . $last . "!";
echo $greeting, "\n";

$label = "Status: ";
$label .= "Active";
echo $label, "\n";
?>

How It Works

The dot operator joins strings left to right. The .= assignment appends to an existing variable—handy when building HTML or log lines in a loop.

Example 4 — Common String Helpers

Transform text with built-in functions—each returns a new string without changing the original.

PHP
<?php
$original = "  Hello, World!  ";

$trimmed   = trim($original);
$lower     = strtolower($trimmed);
$upper     = strtoupper($trimmed);
$greeting  = str_replace("Hello", "Greetings", $trimmed);

echo "Original: [$original]\n";
echo "Trimmed:  [$trimmed]\n";
echo "Lower:    $lower\n";
echo "Upper:    $upper\n";
echo "Replaced: $greeting\n";
?>

How It Works

trim() removes leading and trailing whitespace. Case functions change letters. str_replace() swaps one substring for another. The original $original stays unchanged—always assign the return value.

Example 5 — Split and Join (explode / implode)

Turn comma-separated text into an array, then join it back with a different separator—one of the most common string patterns in PHP.

PHP
<?php
$csv  = "apple,banana,cherry";
$tags = explode(",", $csv);

echo "Item count: ", count($tags), "\n";
echo "First item: ", $tags[0], "\n";
echo "Joined: ", implode(" | ", $tags), "\n";
echo "Upper tags: ", implode(", ", array_map("strtoupper", $tags)), "\n";
?>

How It Works

explode() splits on a delimiter; implode() (alias join()) merges array elements. Together they handle comma-separated lists, tag strings, and similar everyday tasks.

🚀 Common Use Cases

  • User input — store and validate names, emails, and comments as strings.
  • HTML output — build page content and escape user data with htmlspecialchars().
  • CSV and lists — split comma-separated values with explode(), join tags with implode().
  • URLs and paths — concatenate base URLs, query strings, and file paths.
  • Data encoding — convert binary to hex, encode HTML entities, hash passwords.
  • Debugging — inspect values with echo, var_dump(), or log strings to files.

🧠 How PHP Strings Work

1

You create a string

Assign text with quotes, heredoc, or by reading input from forms, files, or databases.

Create
2

PHP stores bytes in memory

Strings are byte sequences. With UTF-8, one visible character may use one to four bytes.

Storage
3

Helpers transform or analyze

Built-in helpers trim, split, escape, or encode the string and return a new result.

Transform
=

Output or storage

Echo to the browser, save to a database, or pass to the next step in your app.

📝 Notes

  • strlen() counts bytes, not always visible characters—use mb_strlen() for Unicode-aware length.
  • Built-in helpers return new values; the original variable stays unchanged unless you reassign.
  • Always escape user input before embedding in HTML: htmlspecialchars(..., ENT_QUOTES, "UTF-8").
  • Prefer prepared statements over manual escaping for SQL safety.
  • Some helpers return false on failure—check before use.
  • PHP string helpers are called as global functions, not methods on a string object.

Conclusion

Strings are the backbone of PHP text handling. Master quote styles, concatenation, and a handful of common helpers like trim(), strlen(), explode(), and implode()—and you are ready to build real web pages and scripts.

Practice the examples on this page, then combine strings with echo to output dynamic content safely in HTML.

💡 Best Practices

✅ Do

  • Use UTF-8 everywhere (files, database, HTTP headers)
  • Pick single quotes when you do not need variable expansion
  • Assign helper results to variables
  • Escape user data with htmlspecialchars() in HTML
  • Use explode() / implode() for CSV and tag lists

❌ Don’t

  • Assume strlen() equals visible character count for UTF-8
  • Build SQL with unescaped user strings
  • Mix encodings (Latin-1 file + UTF-8 database)
  • Forget to trim() form input before validation
  • Output raw user HTML without escaping

Key Takeaways

Knowledge Unlocked

Five things to remember about PHP strings

Use these points as you write your first PHP programs.

5
Core concepts
📝 02

Two Quote Styles

Single vs double.

Syntax
🔗 03

Concatenate with .

Join string pieces.

Operator
🛠 04

Built-in Functions

trim, case, replace.

Helpers
📚 05

Safe Output

Escape user data.

Security

❓ Frequently Asked Questions

A string is a sequence of characters used to store and manipulate text—names, messages, HTML, file paths, and more. In PHP you write strings in single quotes, double quotes, or heredoc/nowdoc syntax. The string type is one of PHP's most common data types.
Double-quoted strings expand variables and many escape sequences ("Hello, $name"). Single-quoted strings are mostly literal—only \\ and \' are special ('Hello, $name' prints $name literally). Use single quotes when you do not need variable expansion.
Use the concatenation operator dot (.): $full = $first . ' ' . $last;. You can also use .= to append: $text .= ' more';. For output, echo accepts comma-separated pieces: echo 'Hi ', $name, '!';
No. PHP passes strings by value (copy-on-write internally). Helpers like strtoupper(), trim(), and htmlspecialchars() return a new string. Assign the result: $upper = strtoupper($text);
strlen() returns the byte length of a string—not always the number of visible characters in UTF-8. For Unicode-aware length, use mb_strlen($text, "UTF-8"). It is a common first helper to learn after creating strings.
Learn echo and basic string creation first (this page). Practice single vs double quotes, concatenation with the dot operator, and helpers like trim(), strtolower(), explode(), and implode() in the examples above.
Did you know?

PHP strings are byte sequences, not objects with methods. You call global functions like strlen($text) instead of $text->length(). Always use UTF-8 so international characters store and display correctly.

Practice with PHP echo

Combine what you learned about strings with echo to output dynamic text in your programs.

PHP echo tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful