If you've written JavaScript before, your hands will type "Total: " + 36 without thinking and expect Total: 36. PHP stops with a TypeError instead. In PHP, text is joined with a dot. The dot is only one of several string rules in PHP that differ from JavaScript.
A string is text: a menu item's name, a receipt, an error message, even the whole HTML page PHP sends. Picture a receipt at Mrs. Tini's Stall. Its sentence is always the same, "Order: ... portions of ..., total $...". Only the numbers and the menu item change with each order. In PHP, the part of the sentence that never changes is written as pieces of text, and the parts that change come from variables. Then you can work with the text using PHP's built-in functions: count its length, replace a word, or turn it into capitals.
Double quotes and single quotes
This code writes the same sentence twice: with double quotes, then with single quotes.
<?php
$menu = "Chicken Noodles";
$quantity = 3;
echo "Order $quantity portions of $menu\n";
echo 'Order $quantity portions of $menu\n';
Order 3 portions of Chicken Noodles
Order $quantity portions of $menu\n
- In double quotes,
$quantityand$menuare replaced by their values (interpolation), and\nbecomes a new line. To write the dollar sign itself, put a backslash in front:\$. - In single quotes, everything is written as it is:
$menustays the text$menu,\nstays two characters. Soecho 'Hello $name';writesHello $name, not the person's name. - When a letter comes right after the variable, use curly braces:
"{$quantity}x"writes3x. Without them,"$quantityx"is read as the variable$quantityx, and PHP givesWarning: Undefined variable $quantityx.
Joining with the dot
This receipt is built from pieces of text and variables:
<?php
$menu = "Chicken Noodles";
$total = 36;
$receipt = "Order: " . $menu . ", total \$" . $total;
$receipt .= " (paid)";
echo $receipt;
Order: Chicken Noodles, total $36 (paid)
.(the dot) joins two strings into one. Numbers are turned into text along the way..=adds text to the end of what a variable already holds.- Don't use
+as in JavaScript: at"Total: " + 36, PHP stops with the errorUncaught TypeError: Unsupported operand types: string + int.
Tidy numbers on a receipt. A price on a receipt shows its cents: 36.00, not 36. number_format sets the decimals and the thousands separators, and printf lines up the columns:
<?php
$total = 36;
echo number_format($total, 2) . "\n";
echo number_format($total, 2, ",", ".") . "\n";
printf("%-16s %8s\n", "Chicken Noodles", number_format($total, 2));
printf("%-16s %8s\n", "Iced Tea", number_format(10, 2));
36.00
36,00
Chicken Noodles 36.00
Iced Tea 10.00
number_format($total, 2)writes two decimals after a dot, and a comma between thousands:36.00here,1,250.00for 1250. The second argument is the number of decimals, the next two are the decimal sign and the thousands separator. Sonumber_format($total, 2, ",", ".")gives36,00, the style many countries use.printfwrites text by a pattern, the first string in the brackets. In the pattern,%-16sis replaced by the argument after the pattern, for example "Chicken Noodles", and filled with spaces to 16 characters, aligned left.%8sis replaced by the next argument, the price, made 8 characters wide and aligned right. As a result, the numbers on the receipt line up.sprintfuses the same patterns, but it returns the string as its result instead of writing it. You can store that result in a variable.
A heredoc for text over several lines
A receipt of two lines can be written as a heredoc: you write the text line by line, with no dots and no \n.
<?php
$menu = "Chicken Noodles";
$quantity = 3;
$total = 36;
$receipt = <<<RECEIPT
Order: $quantity portions of $menu
Total: \$$total
RECEIPT;
echo $receipt;
Order: 3 portions of Chicken Noodles
Total: $36
<<<RECEIPTopens text over several lines, andRECEIPT;on its own line closes it. You can use any word instead of RECEIPT, as long as the opening and closing match.- A heredoc works like double quotes: its variables are replaced by their values.
- The version that works like single quotes is called a nowdoc, written
<<<'RECEIPT': nothing inside is changed at all.
String functions you'll use a lot
These six built-in functions work on one sentence:
<?php
$sentence = "I Am Learning PHP";
echo strlen($sentence) . "\n";
echo strtolower($sentence) . "\n";
echo strtoupper($sentence) . "\n";
echo str_replace("PHP", "Laravel", $sentence) . "\n";
echo substr($sentence, 5, 8) . "\n";
var_dump(str_contains($sentence, "PHP"));
17
i am learning php
I AM LEARNING PHP
I Am Learning Laravel
Learning
bool(true)
strlen($sentence)counts its length. Spaces count too: 1 + 1 + 2 + 1 + 8 + 1 + 3 = 17. Another example:strlen("Learning")gives8.strtolowermakes every letter lower case,strtoupperevery letter upper case.str_replace(search, replace, text)returns a new string with the word replaced.$sentenceitself doesn't change, so the result has to be echoed or stored.substr(text, start, length)takes a piece of the text. Positions count from 0, so position 5 is the L of "Learning". From there it takes 8 characters:Learning.str_contains(available since PHP 8) answerstruewhen the word "PHP" is in$sentence, andfalsewhen it isn't. One more you'll use often:trimremoves the spaces at both ends of the text.
strlen counts bytes
"Café Crème" has 10 characters, the space included. Before looking at the result, guess: does strlen answer 10 or 12?
<?php
$menu = "Café Crème";
echo strlen($menu) . "\n";
echo mb_strlen($menu) . "\n";
echo strtoupper($menu) . "\n";
echo mb_strtoupper($menu) . "\n";
12
10
CAFé CRèME
CAFÉ CRÈME
- PHP stores a string as a row of bytes (a unit of data size in a computer). The way it stores the letters is called UTF-8: a plain letter or a space takes 1 byte, an accented letter like é takes 2.
strlencounts bytes, so "Café Crème", which has 10 characters, counts 12.- The functions that start with
mb_(multibyte) count and change character by character:mb_strlenanswers 10, andmb_strtouppercapitalises the é and è too. Plainstrtoupperleaves them in lower case. - For text without accents, such as "I Am Learning PHP",
strlenandmb_strlengive the same result.
⚠️ Wrong joins and wrong quotes
- Joining with
+. In PHP,+is only for numbers. Join text with the dot. - Variables in single quotes.
'Hello $name'writesHello $name. A sentence that uses variables goes in double quotes. - Thinking
str_replacechanges the variable.str_replacereturns a new string. Writeecho str_replace(...)or store the result in a variable. - Upper and lower case.
str_replace("php", "Laravel", $sentence)replaces nothing, because the sentence saysPHP.str_ireplaceignores case.
TL;DR: A string is text. Double quotes replace a $variable with its value and turn \n into a new line, single quotes write everything as it is ('Hello $name' stays Hello $name). Text is joined with the dot (.), not +, and .= adds text to the end of a variable. Text over several lines is neatest as a heredoc <<<RECEIPT ... RECEIPT;. strlen counts the length, spaces included ("I Am Learning PHP" = 17, "Learning" = 8). strtolower/strtoupper change the letters to lower/upper case, and str_replace(search, replace, text) returns a new string and leaves the original as it was. strlen counts bytes (units of data), and an accented letter takes 2 bytes. So for accented text such as "Café Crème", use mb_strlen and the other mb_ functions.
⚡ Double quotes or single quotes
Write:
<?php
$menu = "Chicken Noodles";
$quantity = 3;
echo "Order $quantity portions of $menu\n";
echo 'Order $quantity portions of $menu\n';
Guess first: what does the second echo (with single quotes) write?
Order $quantity portions of $menu\n, exactly as it is. In single quotes, variables and \n (the new line sign) aren't processed. The first echo writes Order 3 portions of Chicken Noodles.
Meaning: A sentence that uses variables goes in double quotes, because only double quotes replace a variable with its value.
⚡ Joining with the dot
Write:
$receipt = "Order: " . $menu . ", total \$" . $total;
$receipt .= " (paid)";
Meaning: $menu and $total hold the menu item's name and the total price. . joins two strings, and .= adds text to the end of the text already in $receipt. Don't use + as in JavaScript: the result is a TypeError.
⚡ String functions
Write:
<?php
$sentence = "I Am Learning PHP";
echo strlen($sentence) . "\n";
echo strtolower($sentence) . "\n";
echo str_replace("PHP", "Laravel", $sentence) . "\n";
Meaning: strlen counts the length, spaces included: 17. strtolower makes every letter lower case. str_replace returns a new string, with "PHP" replaced by "Laravel". $sentence itself doesn't change, so the result has to be echoed or stored.
⚡ strlen counts bytes
Guess first: "Café Crème" has 10 characters, the space included. What does strlen answer?
12. An accented letter like é takes 2 bytes (units of data), and strlen counts bytes. mb_strlen answers 10.
Meaning: For accented text, use the functions that start with mb_, such as mb_strlen, which counts characters, not bytes.