Variables & Data Types
Store data in variables — every PHP variable starts with a dollar sign.
What you will learn
- Create variables with $
- Use the main data types
- Output variables inside strings
Variables start with $
A variable is a labelled box that stores a value so you can use it later. Every PHP variable begins with $, then a name you choose. You do not declare a type — PHP figures out on its own whether you stored text, a number, and so on.
<?php
$name = "Asha";
$age = 22;
$price = 99.50;
$isStudent = true;
echo "Name: " . $name; // join with a dot
echo "<br>Age: " . $age;
?>The first four lines store values: text in $name, a whole number in $age, a decimal in $price, and a true/false value in $isStudent. The = means "put the value on the right into the box on the left". The two echo lines then glue the label text and the stored value together with a dot . and print them.
Note: Output (in the browser):
Name: Asha
Age: 22
The dot . joined "Name: " with whatever was inside $name to make one piece of text. The <br> inside the second echo pushed "Age:" onto a new line.
Watch out: PHP joins strings with a dot ., not a plus. "Hi " . $name is correct; "Hi " + $name is not.
Variables inside double-quoted strings
There is a shortcut for joining: inside double quotes, PHP swaps a variable for its value automatically (this is called *interpolation*). Inside single quotes, it does not — you get the variable name as literal text.
<?php
$name = "Asha";
echo "Hello, $name!"; // Hello, Asha!
echo 'Hello, $name!'; // Hello, $name! (single quotes — literal)
?>Note: Output (in the browser):
Hello, Asha!Hello, $name!
Double quotes turned $name into Asha. Single quotes printed the characters $name exactly as written — they do not look inside variables. Remember the rule: double quotes read variables, single quotes do not.
| Type | Example |
|---|---|
| String | "Hello" |
| Integer | 42 |
| Float | 99.5 |
| Boolean | true / false |
| Array | ["a", "b"] |
| NULL | null |
Q. How do you join two strings in PHP?
✍️ Practice
- Create variables for your name, age and city, then echo a sentence using them.
- Show the difference between double-quote and single-quote variable insertion.
🏠 Homework
- Build a “profile” PHP page that stores your details in variables and outputs them as HTML.