Strings in PHP

I. How to declare a string in PHP

String is a series of characters. We can wrap a string in single quotes or double quotes.

$x = "Hello";
echo $x; // Hello

However, we can only use variables in double-quote, not single-quote.

$firstName = "Dev";
echo 'Hello $firstName'; // Hello $firstName
echo "Hello $firstName"; // Hello Dev

II. String concatenation

In PHP, we can join strings together using dot . operator.

$x = "Hello";
$y = "World";
$c = $x." ".$y;

III. Escape character

We can use the backslash \ as an “escape” character. \n doesn’t work inside of a single-quoted string.

echo "Hello. \"This string's in double quotes.\" ";
// Hello. "This string's in double quotes."

IV. Access a letter in a string

We can use a zero-based index to access a letter in a string.

The first letter is in a 0 position. A minus position is counted from the end of a string.

$x = "Hello World";
echo $x[1]; // e
echo $x[-3]; // r

We can also change a letter in a string by using bracket the same way.

$x = "Hello World";
$x[4] = "y";
echo $x; // Helly World

V. heredoc and nowdoc syntax

We can use also use heredoc and nowdoc to declare a string.

They help improving the readability of the code.

1. heredoc

PHP heredoc strings are like double-quoted strings, without the double-quotes. So they don’t need to escape quotes and expand variables.

We can start with the <<< operator and an identifier.

$str = <<<TEXT
a string
can span multiple lines
and include single quote ' and double quotes "
TEXT;

Example:

<?php
$x = "a";
$y = "b";
$z = "c";
echo <<<TEXT
Line 1 $x
Line 2 $y
Line 3 $z
TEXT;

// Line 1 a Line 2 b Line 3 c

2. nowdoc

nowdoc is similar to single-quoted string, so we can’t use variables inside nowdoc.

<?php
$name = "Dev";
echo <<<'TEXT'
My name is "$name". I am going $a->b.
TEXT;
// My name is "$name". I am going $a->b.