What is a Variable?
Imagine you have a set of labeled boxes. You can put something inside a box, and you can change its contents later. In programming, a variable is exactly that: a container for storing information.
Variables allow you to store data, like a username or a product price, give it a name, and then refer to it or manipulate it later in your code. This is a fundamental concept in all programming languages.
Declaring Variables in PHP
The syntax for creating a variable in PHP is simple:
- It must start with a dollar sign (
$
). - The name must start with a letter or an underscore (
_
). It cannot start with a number. - The name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _).
- Variable names are case-sensitive!
$name
and$NAME
are two different variables.
<?php
// Assigning a text value to a variable
$username = "Alex";
// Assigning a number value to a variable
$user_age = 30;
// Using the variable's value
echo "The user's name is ";
echo $username;
?>
PHP Data Types
Variables can store different types of data. While PHP is smart enough to figure out the type automatically (this is called "loose typing"), it's important to know the main types you'll be working with.
- String: A sequence of characters, like "Hello world!". Must be enclosed in single (
'
) or double ("
) quotes. - Integer: A whole number without a decimal point, like
-5
,0
, or150
. - Float (or Double): A number with a decimal point, like
3.14
or99.95
. - Boolean: Represents only two possible states:
true
orfalse
. They are often used for conditional checks. - NULL: A special data type that means "no value." It's used to represent an empty or unassigned variable.
Concatenation: Combining Strings
To join strings and variables together, PHP uses the dot (.
) operator. This is called concatenation.
<?php
$product = "E-book";
$price = 19.99;
echo "The price for the " . $product . " is $" . $price;
// Output: The price for the E-book is $19.99
?>
Variables are the foundation upon which you'll build every program. In the next lesson, we'll learn how to perform calculations and comparisons with them using operators.