Variables and Strings
Teaching PHP to remember words and reuse them
So far, everything you echoed was typed by hand. Real websites are more interesting than that: they greet users by name, show product titles, and display messages that change. To do any of that, PHP needs a way to remember values. That is what variables are for.
Making a variable
In PHP, every variable starts with a dollar sign. You create one by giving it a name and a value with the equals sign:
<?php
$name = "Ada";
$greeting = "Welcome back";
echo $greeting;
?>Read $name = "Ada"; as: put the text Ada into a box labeled name. From then on, whenever PHP sees $name, it looks in the box and uses whatever is inside.
Naming rules
- Every variable starts with
$. - After the dollar sign, start with a letter or underscore, never a number.
$user2is fine;$2useris not. - Names are case sensitive:
$Nameand$nameare two different boxes. - Pick names that describe the contents. Future you will thank present you for
$customerEmailinstead of$x.
Strings: text in quotes
A piece of text in quotes is called a string. PHP accepts single quotes and double quotes, and the difference actually matters.
With double quotes, PHP looks inside the string for variables and swaps in their values:
<?php
$name = "Ada";
echo "Hello, $name!";
?>This prints Hello, Ada! because PHP replaced $name with its value. With single quotes, PHP takes the text completely literally:
<?php
$name = "Ada";
echo 'Hello, $name!';
?>This prints Hello, $name! with the dollar sign and all. Beginners usually reach for double quotes so that variables work inside them.
Gluing strings together
You can join strings with a dot, which PHP calls concatenation:
<?php
$first = "Grace";
$last = "Hopper";
$full = $first . " " . $last;
echo "The full name is " . $full . ".";
?>The dot simply sticks one string onto the end of another. Here we glued the first name, a space, and the last name into $full, then built a sentence around it.
Variables can change
The value in a variable is not locked in. Assign again and the old value is replaced:
<?php
$mood = "sleepy";
$mood = "caffeinated";
echo $mood;
?>This prints caffeinated, because the second assignment overwrote the first. That ability to change is exactly why they are called variables.
Quick recap: variables start with $, strings live in quotes, double quotes let variables work inside the text, and the dot glues strings together. These four facts cover a surprising amount of everyday PHP.
Quick check
Q1 Which of these is a valid PHP variable name?
Q2 If $city contains "Paris", what does echo "I love $city"; print?
Want to save your progress? It's free.
Create a free account