Skip to content
Lesson 4 of 17

Step 1 of 5 · Reading · ~4 min

Learn

Strings

Strings

PHP gives you two ways to write a string literal, and picking the wrong one is the single most common beginner bug in the language.

Single or double quotes?

Double "..."Single '...'
A variable insideinterpolated into the textprinted literally
\n, \ta real newline / taba literal backslash and letter
Speedidentical in practiceidentical in practice
<?php
$city = "Lisbon";
echo "Route to $city\n";
echo 'Route to $city\n';

//> Route to Lisbon
//> Route to $city\n

The second echo printed a dollar sign, the variable name, and a literal backslash-n — and no line break at all, so anything printed after it lands on the same line.

Use double quotes when you want interpolation or escapes; use single quotes for fixed text. Both are fine. Be deliberate.

What if the variable name runs into the next word?

PHP stops reading a variable name at the first character that cannot be part of one. That works in "Route to $city\n", because a backslash ends the name — but it fails the moment real letters follow. Wrap the expression in braces:

<?php
$size = "large";
echo "a {$size}r box\n";
$parcel = ["city" => "Lisbon", "kg" => 1.75];
echo "Going to {$parcel['city']}\n";

//> a larger box
//> Going to Lisbon

Braces are also mandatory for a quoted array key: "$parcel['city']" is a parse error, while "{$parcel['city']}" works.

Joining strings

. concatenates. + never does — it is arithmetic, always.

✗ Wrong✓ Right
"ship" + "ment""ship" . "ment"
$msg = $msg + $extra;$msg .= $extra;

.= appends in place, exactly the way += adds in place.

The toolbox you will actually use

FunctionExampleResult
strlenstrlen("Lisbon")6
trimtrim(" Lisbon ")"Lisbon"
strtoupper / strtolowerstrtoupper("Lisbon")"LISBON"
ucfirstucfirst("lisbon")"Lisbon"
substrsubstr("Lisbon", 0, 3)"Lis"
substr with a negative startsubstr("Lisbon", -3)"bon"
str_replacestr_replace("Lisbon", "Porto", "Lisbon depot")"Porto depot"
str_repeatstr_repeat("-", 10)"----------"

The naming is inconsistent — strlen and str_replace come from different eras of PHP. There is no rule to learn; you look them up.

Splitting and joining lines

Almost every exercise from here on begins by cutting a line of input into pieces. Two functions do all of it:

<?php
$line  = "3 8 2 9 1";
$parts = explode(" ", $line);
echo count($parts), "\n";
echo $parts[0], "\n";
echo implode(", ", $parts), "\n";

//> 5
//> 3
//> 3, 8, 2, 9, 1

explode(separator, string) gives you an array; implode(glue, array) puts one back together. The argument orders are mirror images of each other, which is worth a second look every time you write one.

The strpos trap

strpos returns the index where it found the needle, or false when it did not find it at all. Index 0 is a perfectly good answer — and 0 is falsy.

<?php
var_dump(strpos("Lisbon", "Lis"));   // found at the very start
var_dump(strpos("Lisbon", "zzz"));   // not found

//> int(0)
//> bool(false)
✗ Wrong✓ Right
if (strpos($s, $x))if (strpos($s, $x) !== false)

The wrong version quietly reports "not found" whenever the match sits at position 0. PHP 8 added str_contains() to make this readable, but this course's grader runs PHP 7.4, so !== false is what you write here.

Your exercise

Greeting Card reads a name and an age and prints one line in the shape Hi, Alice! You are 25 years old.

The starter has both values ready, so the job is a single echo using double-quoted interpolation. The mistake the grader catches is single quotes: wrapped in '...', your program prints the literal text Hi, $name! You are $age years old. followed by a literal backslash-n, and every test fails at once. The punctuation is graded too — comma after Hi, exclamation mark straight after the name, full stop at the very end. Finish the line with a real "\n": trailing whitespace is trimmed before the comparison so this single line would pass without it, but the habit is what keeps multi-line answers correct later on.

Up nextsprintf and HeredocStrings

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…