Core PHP 7 programs with output 15 Q/A 5 MCQs

Learning Objectives – after this chapter you will be able to:

  • Explain how PHP stores strings and how large a string can be.
  • Write string literals in the four syntaxes: single-quoted, double-quoted, heredoc and nowdoc.
  • Use escape sequences and variable parsing (interpolation) in double-quoted strings.
  • Apply common string functions such as strlen(), strpos(), str_replace() and substr().
Strings in PHP

A string is a series of characters. In PHP a character is the same as a byte, so there are exactly 256 different characters possible. Text in UTF-8 (for example Hindi: नमस्ते) uses several bytes per character; for such text use the multibyte functions mb_strlen(), mb_substr() and so on. (Older books suggest utf8_encode()/utf8_decode(); these are deprecated since PHP 8.2 – use mb_convert_encoding() instead.)

It is no problem for a string to become very large. PHP imposes no fixed limit on the size of a string; the only limit is the memory available to the script (memory_limit in php.ini).

A string literal can be specified in four different ways:

  • single quoted
  • double quoted
  • heredoc syntax
  • nowdoc syntax
Single-Quoted Strings

The simplest way to specify a string is to enclose it in single quotes (').

  • To specify a literal single quote, escape it with a backslash: \'.
  • To specify a literal backslash, double it: \\.
  • All other backslashes are treated literally: escape sequences such as \r or \n are output as written, without any special meaning.
  • Variables are not expanded inside single-quoted strings.
File: htdocs/phpbook/ch08/single.php
<?php
echo 'this is a simple string';
echo '<br>';
echo 'You can also have embedded newlines in
strings this way as it is okay to do';
echo '<br>';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
echo '<br>';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
echo '<br>';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
echo '<br>';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
echo '<br>';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
OUTPUT browser · http://localhost/phpbook/ch08/single.php
this is a simple string
You can also have embedded newlines in strings this way as it is okay to do
Arnold once said: "I'll be back"
You deleted C:\*.*?
You deleted C:\*.*?
This will not expand: \n a newline
Variables do not $expand $either

(The newline inside the second string is displayed as a space, because the browser treats line breaks in HTML as white space.)

Double-Quoted Strings

If the string is enclosed in double quotes ("), PHP interprets more escape sequences:

SequenceMeaning
\nlinefeed (LF, ASCII 10)
\rcarriage return (CR, ASCII 13)
\thorizontal tab (HT, ASCII 9)
\vvertical tab (VT, ASCII 11)
\eescape (ESC, ASCII 27)
\fform feed (FF, ASCII 12)
\\backslash
\$dollar sign
\"double quote
\[0-7]{1,3}character in octal notation, e.g. \101 is "A"
\x[0-9A-Fa-f]{1,2}character in hexadecimal notation, e.g. \x41 is "A"
\u{hex}Unicode code point as UTF-8, e.g. \u{20B9} is "₹"

As in single-quoted strings, escaping any other character prints the backslash too. The most important feature of double-quoted strings is that variable names are expanded (variable parsing / interpolation).

File: htdocs/phpbook/ch08/double.php
<?php
$name = "Asha";
$fruits = ["apple", "mango"];
$user = ["city" => "Bhopal"];
echo "<pre>";
echo "Hello $name!\n";
echo "Tab\tseparated\tvalues\n";
echo "A quote: \" and a dollar: \$name\n";
echo "Octal \101, hex \x41, rupee \u{20B9}\n";
echo "First fruit: $fruits[0]\n";
echo "City: {$user['city']}\n";        // curly syntax for complex expressions
echo "Name in capitals: " . strtoupper($name) . "\n";
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch08/double.php
Hello Asha!
Tab	separated	values
A quote: " and a dollar: $name
Octal A, hex A, rupee ₹
First fruit: apple
City: Bhopal
Name in capitals: ASHA
Simple and complex (curly) syntax

A simple variable such as $name or $fruits[0] can be written directly inside double quotes. For array elements with string keys, object properties or anything more complex, wrap the expression in curly braces: "{$user['city']}", "{$obj->name}".

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator an identifier is given, then a new line. The string follows, and then the same identifier again to close the quotation.

  • The identifier must follow the same naming rules as other labels in PHP: only letters, digits and underscores, not starting with a digit.
  • Heredoc text behaves just like a double-quoted string without the double quotes: quotes need not be escaped, escape codes work and variables are expanded.
  • Since PHP 7.3 the closing identifier may be indented, and the same amount of indentation is removed from every line of the text. In older versions it had to start in the first column, with nothing but an optional ; after it.
  • Heredoc can be used to initialise static variables, class properties and constants (with static values).
File: htdocs/phpbook/ch08/heredoc.php
<?php
class Foo
{
    public $foo;
    public $bar;
    function __construct()
    {
        $this->foo = 'Foo';
        $this->bar = array('Bar1', 'Bar2', 'Bar3');
    }
}
$foo = new Foo();
$name = 'MyName';
echo <<<EOT
<pre>
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should print a capital 'A': \x41
</pre>
EOT;
?>
OUTPUT browser · http://localhost/phpbook/ch08/heredoc.php
My name is "MyName". I am printing some Foo.
Now, I am printing some Bar2.
This should print a capital 'A': A

PHP 8 change. Old notes wrote the constructor of class foo as a method also named foo(). Such "PHP 4 style" constructors are no longer constructors in PHP 8; always use __construct() (Chapter 17).

Heredoc is also convenient for passing long text as a function argument, or for building HTML:

File: htdocs/phpbook/ch08/heredoc2.php
<?php
$product = "Laptop";
$price = 45999;
$html = <<<HTML
    <div style="border:1px solid #999;padding:6px;width:220px">
        <b>$product</b><br>
        Price: Rs. {$price}/-
    </div>
    HTML;
echo $html;
echo "<pre>";
var_dump(array(<<<EOD
foobar!
EOD));
echo "</pre>";
?>
OUTPUT browser · http://localhost/phpbook/ch08/heredoc2.php
Laptop
Price: Rs. 45999/-
array(1) {
  [0]=>
  string(7) "foobar!"
}
Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is written like a heredoc, but the identifier is enclosed in single quotes, e.g. <<<'EOT', and no parsing is done inside it: variables are not expanded and escape sequences are not interpreted. It is ideal for embedding PHP code or other large blocks of text without escaping.

File: htdocs/phpbook/ch08/nowdoc.php
<?php
$name = 'MyName';
echo <<<'EOT'
<pre>
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
</pre>
EOT;
?>
OUTPUT browser · http://localhost/phpbook/ch08/nowdoc.php
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Nowdoc (available since PHP 5.3) can be used in any static data context, for example to initialise class properties or constants:

File: htdocs/phpbook/ch08/nowdoc_static.php
<?php
class Notice
{
    const TITLE = <<<'EOT'
Office closed on Monday
EOT;
    public $body = <<<'EOT'
Fees can be paid online at $site.
EOT;
}
$n = new Notice();
echo Notice::TITLE . "<br>" . $n->body;
?>
OUTPUT browser · http://localhost/phpbook/ch08/nowdoc_static.php
Office closed on Monday
Fees can be paid online at $site.
Frequently Used String Functions

Part II gives the complete list of string functions. The following are used in almost every program:

File: htdocs/phpbook/ch08/strfunc.php
<?php
$s = "  Welcome to PHP Programming  ";
$t = trim($s);
echo "trim: '$t'<br>";
echo "strlen: " . strlen($t) . "<br>";
echo "str_word_count: " . str_word_count($t) . "<br>";
echo "strtoupper: " . strtoupper($t) . "<br>";
echo "strtolower: " . strtolower($t) . "<br>";
echo "ucwords: " . ucwords("php and mysqli") . "<br>";
echo "strrev: " . strrev("PHP") . "<br>";
echo "strpos of 'PHP': " . strpos($t, "PHP") . "<br>";
echo "substr(11, 3): " . substr($t, 11, 3) . "<br>";
echo "str_replace: " . str_replace("PHP", "MySQLi", $t) . "<br>";
echo "str_contains (PHP 8): " . (str_contains($t, "come") ? "yes" : "no") . "<br>";
echo "str_pad: " . str_pad("7", 3, "0", STR_PAD_LEFT) . "<br>";
echo "number_format: " . number_format(1234567.891, 2);
?>
OUTPUT browser · http://localhost/phpbook/ch08/strfunc.php
trim: 'Welcome to PHP Programming'
strlen: 26
str_word_count: 4
strtoupper: WELCOME TO PHP PROGRAMMING
strtolower: welcome to php programming
ucwords: Php And Mysqli
strrev: PHP
strpos of 'PHP': 11
substr(11, 3): PHP
str_replace: Welcome to MySQLi Programming
str_contains (PHP 8): yes
str_pad: 007
number_format: 1,234,567.89
Key Takeaways
  • A PHP string is a sequence of bytes; size is limited only by memory. Use mb_* functions for UTF-8 text.
  • Single quotes: only \' and \\ are special; variables are not expanded.
  • Double quotes: escape sequences and variable interpolation; use {…} for complex expressions.
  • Heredoc <<<ID behaves like double quotes; nowdoc <<<'ID' like single quotes.
  • Since PHP 7.3 the heredoc/nowdoc closing identifier may be indented.
  • strlen, strpos, substr, str_replace, trim, strtoupper and str_contains are everyday string functions.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch08 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.

Question / Answer (15 questions)

Answer : A series of characters, where each character is one byte. Strings can hold text of any length limited only by available memory.

Answer : Four – single-quoted, double-quoted, heredoc and nowdoc.

Answer : Only \' for a literal single quote and \\ for a literal backslash. All other backslashes are printed as they are.

Answer : Double-quoted strings expand variables and interpret escape sequences such as \n and \t; single-quoted strings do neither.

Answer : Replacing variable names inside a double-quoted string or heredoc with their values, e.g. "Hello $name" becomes "Hello Asha".

Answer : For array elements with quoted string keys, object properties of objects in arrays, method calls and other complex expressions, e.g. "{$user['city']}" or "{$foo->bar[1]}".

Answer : A way of writing multi-line strings: <<<IDENTIFIER, a new line, the text, then the identifier again. It behaves like a double-quoted string, so variables are expanded and quotes need no escaping.

Answer : A heredoc whose identifier is in single quotes, e.g. <<<'EOT'. No parsing is done inside it – it behaves like a single-quoted string.

Answer : It must match the opening identifier and be the first non-white-space text on its line. Since PHP 7.3 it may be indented (that indentation is removed from all lines) and may be followed by other code; before 7.3 it had to start in column 1 with only an optional semicolon after it.

Answer : In static contexts such as initialising class properties and class constants, because nowdoc contains no variables to parse.

Answer : "\u{20B9}" inside a double-quoted string (PHP 7 and later).

Answer : strlen() counts bytes, and each Devanagari character takes several bytes in UTF-8. mb_strlen() counts characters.

Answer : strpos($s, $find) returns the position of the first occurrence of $find in $s (or false); str_replace($search, $replace, $s) replaces all occurrences of $search with $replace.

Answer : White space (spaces, tabs, new lines, NUL and vertical tab) from the beginning and end of a string; ltrim() and rtrim() remove it from one side only.

Answer : str_contains($haystack, $needle), which returns true or false. PHP 8 also added str_starts_with() and str_ends_with().
MCQ Test : Check Your Understanding (5 questions)

Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.

Q1. What does echo 'Hi\n$x'; print?

Show Answer

Correct Answer : B. Hi\n$x
Single-quoted strings neither interpret \n nor expand variables.

Q2. Which string syntax does NOT expand variables?

Show Answer

Correct Answer : C. Nowdoc
Nowdoc behaves like a single-quoted string.

Q3. A nowdoc identifier is written as:

Show Answer

Correct Answer : C. <<<'EOT'
The identifier in single quotes marks a nowdoc.

Q4. What is "\x41" in a double-quoted string?

Show Answer

Correct Answer : B. A
\x41 is hexadecimal 41, the character A.

Q5. Which function counts characters correctly in UTF-8 text?

Show Answer

Correct Answer : C. mb_strlen()
mb_strlen() is multibyte-aware.

Bibliography/References

The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.

  1. The PHP Group. (n.d.). PHP Manual – Strings. https://www.php.net/manual/en/language.types.string.php
  2. The PHP Group. (n.d.). PHP Manual – String Functions. https://www.php.net/manual/en/ref.strings.php
  3. The PHP Group. (n.d.). PHP Manual – Multibyte String. https://www.php.net/manual/en/book.mbstring.php
  4. The PHP Group. (n.d.). PHP Manual – Migrating from PHP 7.2.x to PHP 7.3.x (flexible heredoc). https://www.php.net/manual/en/migration73.new-features.php