PHP Strings
A string is a piece of text held as one value in PHP. A string can be written with double quotes or with single quotes, and the two forms act differently.
Double quotes use the value
Putting the value of a variable inside text this way is called interpolation.
<?php
$name = "Hana";
echo "Hello $name\n";Single quotes keep the text plain
The same greeting in single quotes prints the dollar sign and the name as plain characters.
<?php
$name = "Hana";
echo 'Hello $name', "\n";The dot joins pieces
Each dot joins the piece after it onto the string being built.
<?php
$name = "Hana";
echo "Hello " . $name . "\n";An index reads one character
Index 1 picks the second character of the string.
<?php
echo "Hello"[1], "\n";Spaces stay inside the string
<?php
echo "I live in New York\n";Example
<?php
$name = "Hana";
$city = "Oslo";
echo "Hello $name from $city\n";
echo "Hello " . $name . " from " . $city . "\n";Key points
- A string holds text as a single value.
- Double quotes let the text include the value of a variable written inside it.
- Single quotes print every character exactly as written.
- Use the dot operator to join strings and values into one longer string.
- An index in square brackets picks one character from a string.
- The first character of a string is at index 0.
In this example, the first line builds the greeting with interpolation inside double quotes. The second line builds the same greeting with dots joining the pieces. Both lines print the same greeting.
Note
In PHP a plus sign adds numbers, and the dot is the operator that joins text.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
A variable $name holds "Ana". What does a double-quoted string with the text "Hi $name" print?