What Variables Do
Variables are one of the first building blocks you will use in PHP. A variable gives a name to a piece of data so you can store it, reuse it, and update it as your program runs.
Instead of repeating the same value over and over, you can place it in a variable and refer to that name later. This makes your code easier to read and easier to maintain.
How PHP Variables Work
In PHP, every variable starts with a dollar sign. After the dollar sign, you give the variable a name.
$name = “Alice”;
In this example, $name stores the text value Alice. The equal sign assigns the value on the right to the variable on the left.
Common Variable Types
PHP variables can hold many kinds of data. Here are a few common examples:
- Strings for text, like “Hello”
- Integers for whole numbers, like 42
- Floats for decimal numbers, like 3.14
- Booleans for true or false values
$title = “PHP Basics”;
$lessonCount = 8;
$price = 0.00;
$isPublished = true;
Naming Variables Clearly
Choose names that describe the data they hold. Clear names make your code easier to understand.
- Use $firstName instead of $x
- Use $totalPrice instead of $tp
- Use $isLoggedIn for true or false values
Good variable names help both you and other developers understand what the code is doing at a glance.
Updating Variable Values
You can change a variable by assigning a new value to it later in the script.
$score = 10;
$score = 15;
After the second line runs, the value of $score is 15.
Simple Example
Here is a short example that combines a few variables:
$course = “PHP Fundamentals”;
$student = “Maya”;
$completedLessons = 3;echo $student . ” is studying ” . $course . “.”;
echo ” Completed lessons: ” . $completedLessons;
This lets you build dynamic output from stored values.
Key Takeaway
PHP variables store data that your program can use and change. Once you understand variables, it becomes much easier to work with conditionals, loops, arrays, and functions.