PHP Tutorial · PHP Basics · Lesson 8 of 38

PHP Strings

Single vs double quotes, concatenation, heredoc and common string functions.

Single vs double quotes

  • Double quotes expand variables and escape sequences like \n.
  • Single quotes are literal — faster to reason about for fixed text.

Join strings with the . operator (not +), and append with .=:

Example 1Try it yourself
<?php
$name = "Ada";
echo "Hello $name\n";
echo 'Hello $name\n', "\n";
$greeting = "Hello";
$greeting .= ", " . $name . "!";
echo $greeting, "\n";

Output

Hello Ada
Hello $name\n
Hello, Ada!

Common string functions

Example 2Try it yourself
<?php
$s = "  The quick brown fox  ";
echo trim($s), "\n";
echo strtoupper(trim($s)), "\n";
echo ucwords("the quick brown fox"), "\n";
echo strlen("hello"), "\n";
echo str_replace("quick", "slow", $s), "\n";
echo substr("JavaScript", 0, 4), "\n";
var_dump(str_contains("php is fun", "fun"));
echo strrev("php"), " ", str_pad("7", 3, "0", STR_PAD_LEFT), "\n";

Output

The quick brown fox
THE QUICK BROWN FOX
The Quick Brown Fox
5
  The slow brown fox  
Java
bool(true)
php 007

PHP 8 added str_contains(), str_starts_with() and str_ends_with() — much clearer than strpos() !== false.

Multibyte strings

strlen() counts bytes. For text with accents or emoji use the mb_* functions:

Example 3Try it yourself
<?php
$word = "café";
echo strlen($word), " bytes, ", mb_strlen($word), " characters\n";
echo mb_strtoupper($word), "\n";

Output

5 bytes, 4 characters
CAFÉ

Heredoc

Heredoc syntax is handy for multi-line text with variables:

Example 4Try it yourself
<?php
$name = "Ada";
$total = 42.5;
echo <<<TEXT
Dear $name,
Your order total is \${$total}.
Thanks!
TEXT;
echo "\n";

Output

Dear Ada,
Your order total is $42.5.
Thanks!

Test yourself

Which operator joins two strings in PHP?

  1. +
  2. .
  3. &
  4. ++
Show answer

Answer: .