PHP — Strings
String creation
PHP offers several ways to create strings:
<?php
$single = 'Hello'; // Single-quoted (literal)
$double = "Hello"; // Double-quoted (interpolation)
$heredoc = <<<EOT
This string spans
multiple lines
EOT;
$nowdoc = <<<'EOT'
This is literal text
No interpolation happens
EOT;
echo $heredoc;
echo $nowdoc;
?>
String interpolation
Double-quoted strings and heredocs expand variables:
<?php
$name = "Alice";
$greeting = "Hello, $name!"; // Direct variable
$expr = "Sum: " . (3 + 4); // Expression in concatenation
$complex = "Hello, {$name}!"; // Complex syntax
$nested = "Hello, ${name}!"; // Alternative syntax
// Array interpolation
$person = ["name" => "Bob", "age" => 25];
echo "Name: {$person['name']}, Age: {$person['age']}";
?>
Escape sequences
| Sequence | Result |
|---|---|
\n | Newline |
\r | Carriage return |
\t | Tab |
\\ | Backslash |
\$ | Dollar sign |
\" | Double quote |
\0 | Null byte |
<?php
echo "First line\nSecond line";
echo "Tab\there";
echo "Price: \$100";
?>
String concatenation
Use the . operator to join strings:
<?php
$first = "Hello";
$second = "World";
$result = $first . " " . $second; // "Hello World"
// .= appends to a string
$log = "";
$log .= "Error: connection failed\n";
$log .= "Retrying in 5 seconds\n";
echo $log;
?>
Multiline strings
Heredoc preserves formatting without escape sequences:
<?php
$html = <<<HTML
<div class="container">
<h1>$title</h1>
<p>$description</p>
</div>
HTML;
echo $html;
?>
Nowdoc works like heredoc but doesn't interpolate variables — useful for SQL queries or templates:
<?php
$query = <<<'SQL'
SELECT * FROM users WHERE name = 'Alice'
SQL;
echo $query;
?>
String functions
PHP has over 80 built-in string functions. Here are the most common:
<?php
$s = "Hello, World!";
echo strlen($s); // 13 — length
echo strtolower($s); // "hello, world!" — lowercase
echo strtoupper($s); // "HELLO, WORLD!" — uppercase
echo strrev($s); // "!dlroW ,olleH" — reverse
echo trim($s); // "Hello, World!" — remove whitespace
echo str_replace("World", "PHP", $s); // "Hello, PHP!"
echo substr($s, 0, 5); // "Hello" — substring
echo strpos($s, "World"); // 7 — position of first occurrence
?>
Finding and replacing
<?php
$text = "The quick brown fox jumps over the lazy dog.";
echo str_replace("fox", "cat", $text); // Replace all occurrences
echo substr_count($text, "the"); // 2 — case-insensitive count
echo stripos($text, "FOX"); // 16 — case-insensitive position
echo str_contains($text, "fox"); // true (PHP 8+)
echo str_starts_with($text, "The"); // true (PHP 8+)
echo str_ends_with($text, "dog."); // true (PHP 8+)
?>
Formatting
<?php
// sprintf — formatted output
$name = "Alice";
$age = 30;
echo sprintf("Name: %s, Age: %d", $name, $age);
// Number formatting
echo number_format(1234567.891, 2); // "1,234,567.89"
echo number_format(1234567.891, 2, ".", ","); // "1,234,567.89"
// Padding
echo str_pad("42", 5, "0"); // "00042"
echo str_pad("Hi", 10, "-"); // "Hi--------"
?>
Explode and implode
Split and join strings by a delimiter:
<?php
$csv = "apple,banana,cherry";
// Split into array
$fruits = explode(",", $csv);
print_r($fruits);
// Array ( [0] => apple [1] => banana [2] => cherry )
// Join array into string
$joined = implode(" | ", $fruits);
echo $joined; // "apple | banana | cherry"
?>
Type conversion
Convert between strings and other types:
<?php
// To string
echo strval(42); // "42"
echo (string) 3.14; // "3.14"
echo 42 . ""; // "42" — concatenation auto-converts
// From string
echo (int) "42abc"; // 42
echo (float) "3.14xyz"; // 3.14
echo intval("123"); // 123
?>
Mini Practice
Write PHP code that:
- Creates a string with interpolation and prints its length
- Replaces a word in a string and counts occurrences of a character
- Splits a CSV string into an array and joins it back with a different delimiter
- Uses
sprintf()to format a price with 2 decimal places
Up Next
In the next lesson, you'll learn about Operators — arithmetic, comparison, logical, and string operators.
Related Topics
Frequently Asked Questions about Strings
What is Strings in PHP?
Strings is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Strings?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.
Why is Strings important in PHP?
Strings is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.