Variables are fundamental building blocks of any programming language, including PHP. They allow you to store, retrieve, and manipulate data throughout your code. In this guide, we’ll explore everything you need to know about PHP variables to get started effectively.
What Are PHP Variables?
In PHP, variables act as containers that store data values. These values can be numbers, text strings, arrays, objects, boolean values, or even resources like file handles. Unlike some other programming languages, PHP variables don’t require explicit declaration before use, making PHP quite flexible for beginners.
How to Create Variables in PHP
Creating variables in PHP is straightforward:
<?php $name = "John"; $age = 25; $is_student = true; $price = 19.99; ?>
Notice the syntax follows this pattern:
- Each variable name starts with a dollar sign (
$
) - Followed by the variable name
- The assignment operator (
=
) - The value you want to store
PHP Variable Naming Rules
When naming your variables in PHP, follow these rules:
- Must start with a dollar sign (
$
) - The first character after the dollar sign must be a letter or underscore (
_
) - Subsequent characters can be letters, numbers, or underscores
- Variable names are case-sensitive (
$name
and$Name
are different variables) - Cannot contain spaces or special characters like
!
,@
,#
, etc.
Valid vs. Invalid Variable Names
Valid | Invalid | Reason Invalid |
---|---|---|
$name | $1name | Starts with a number |
$first_name | $first-name | Contains a hyphen |
$_user | $user name | Contains a space |
$itemCount | $item% | Contains a special character |
$userID | $user!ID | Contains a special character |
Variable Data Types in PHP
PHP supports several data types for variables:
Data Type | Example | Description |
---|---|---|
String | $name = "John"; | Text enclosed in quotes |
Integer | $age = 25; | Whole numbers without decimal points |
Float | $price = 19.99; | Numbers with decimal points |
Boolean | $is_active = true; | True or false values |
Array | $colors = ["red", "green", "blue"]; | Stores multiple values |
Object | $user = new User(); | Instance of a class |
NULL | $empty = null; | Variable with no value |
Resource | $file = fopen("file.txt", "r"); | Special variable holding a resource |
Variable Scope in PHP
The scope of a variable determines where it can be accessed in your code:
Local Variables
Variables declared within a function are local to that function and cannot be accessed outside of it:
<?php function test() { $local_var = "I'm local!"; echo $local_var; // Works fine } test(); echo $local_var; // Generates an error - variable not accessible here ?>
Global Variables
Variables declared outside all functions are global. To access a global variable inside a function, you need to use the global
keyword:
<?php $global_var = "I'm global!"; function test() { global $global_var; // This line is important echo $global_var; // Now it works } test(); ?>
Static Variables
Static variables retain their value between function calls:
<?php function counter() { static $count = 0; // Initialized only once $count++; echo $count; } counter(); // Outputs: 1 counter(); // Outputs: 2 counter(); // Outputs: 3 ?>
Superglobal Variables
PHP provides several predefined variables called “superglobals” that are always accessible, regardless of scope:
Superglobal | Purpose |
---|---|
$_GET | Collects form data sent with GET method |
$_POST | Collects form data sent with POST method |
$_REQUEST | Collects data from both GET and POST |
$_SESSION | Stores session variables |
$_COOKIE | Stores cookie values |
$_SERVER | Holds server and execution environment information |
$_FILES | Contains uploaded file information |
$_ENV | Holds environment variables |
$GLOBALS | References all variables available in global scope |
Example using a superglobal:
<?php // URL: test.php?name=John echo "Hello, " . $_GET['name']; // Outputs: Hello, John ?>
Variable Assignment and Operations
Basic Assignment
<?php $name = "John"; $age = 30; ?>
Assignment with Operation
<?php $x = 10; $x += 5; // Same as $x = $x + 5; (Result: 15) $x -= 3; // Same as $x = $x - 3; (Result: 12) $x *= 2; // Same as $x = $x * 2; (Result: 24) $x /= 4; // Same as $x = $x / 4; (Result: 6) $x %= 4; // Same as $x = $x % 4; (Result: 2) ?>
Incrementing and Decrementing
<?php $count = 5; $count++; // Increases by 1 (Result: 6) $count--; // Decreases by 1 (Result: 5) // Pre-increment and post-increment behave differently $a = 5; $b = $a++; // $b is 5, $a is 6 $c = 5; $d = ++$c; // $d is 6, $c is 6 ?>
Variable Type Handling
Type Checking
PHP provides functions to check variable types:
<?php $name = "John"; $age = 25; var_dump($name); // string(4) "John" var_dump($age); // int(25) echo gettype($name); // string echo gettype($age); // integer // Specific type checks is_string($name); // true is_int($age); // true is_bool($name); // false is_array($age); // false ?>
Type Casting
You can convert between types using type casting:
<?php $str_number = "42"; $real_number = (int)$str_number; // Convert string to integer $price = 19.99; $whole_price = (int)$price; // Convert float to integer (Result: 19) $count = 0; $is_empty = (bool)$count; // Convert to boolean (Result: false) $value = null; $str_value = (string)$value; // Convert null to string (Result: "") ?>
Variable Variables
PHP allows you to create variable names dynamically:
<?php $foo = "bar"; $$foo = "baz"; // Creates a variable named $bar with value "baz" echo $foo; // Outputs: bar echo $$foo; // Outputs: baz echo $bar; // Outputs: baz ?>
Constants vs. Variables
Unlike variables, constants cannot be changed once defined:
<?php // Define a constant define("PI", 3.14159); // Alternative syntax for constants (PHP 5.3+) const APP_NAME = "My Application"; // Using constants echo PI; // 3.14159 echo APP_NAME; // My Application // This would generate an error // PI = 3.14; // Cannot reassign a constant ?>
Feature | Variables | Constants |
---|---|---|
Syntax | $variable_name | define("CONSTANT_NAME", value) or const CONSTANT_NAME = value |
Dollar sign | Required | Not used |
Reassignment | Can be changed | Cannot be changed |
Scope | Has scope rules | Global by default |
Case sensitivity | Case-sensitive | Case-sensitive (by default) |
Data types | Any type | Primarily scalars (string, number, boolean) |
Frequently Asked Questions (FAQ)
Why do PHP variables start with a dollar sign ($)?
The dollar sign is a sigil that clearly identifies variables in PHP code. This makes it easy to distinguish variables from other code elements like functions, keywords, and constants.
What happens if I try to use a variable that hasn’t been defined?
PHP will generate a notice (depending on your error reporting settings) and treat the variable as having a NULL value. It’s good practice to initialize variables before using them.
What’s the difference between single quotes and double quotes when assigning string values?
Double quotes allow variable interpolation, while single quotes do not:
<?php $name = "John"; echo "Hello $name"; // Outputs: Hello John echo 'Hello $name'; // Outputs: Hello $name (literal) ?>
How do I check if a variable exists or has been set?
Use the isset()
function:
<?php if (isset($username)) { echo "Username is set"; } else { echo "Username is not set"; } ?>
Can I use emojis or Unicode characters in variable names?
Yes, PHP 7.0 and later support Unicode in variable names:
<?php $😊 = "smiley face"; echo $😊; // Outputs: smiley face ?>
However, it’s not recommended in professional code as it reduces readability and can cause compatibility issues.
What’s the difference between unset()
and assigning NULL?
<?php $var1 = "Hello"; $var1 = null; // Variable still exists but has NULL value isset($var1); // Returns false $var2 = "World"; unset($var2); // Variable no longer exists isset($var2); // Returns false ?>
Best Practices for PHP Variables
- Use descriptive names: Choose variable names that clearly describe what they contain.
// Good $user_age = 25; // Bad $ua = 25;
- Be consistent with naming conventions: Choose a style (camelCase, snake_case) and stick with it.
// snake_case $first_name = "John"; // camelCase $lastName = "Doe";
- Initialize variables before use: This prevents notices and unexpected behavior.
$count = 0; while ($count < 10) { // ... }
- Use constants for fixed values: If a value shouldn’t change, make it a constant.
define("MAX_LOGIN_ATTEMPTS", 5);
- Clean up when done: Unset variables when you’re finished with them, especially with large data.
$large_data = get_massive_data(); // Process the data... unset($large_data); // Free up memory
- Avoid global variables: They can lead to spaghetti code and make debugging difficult.
// Instead of global variables, use function parameters function process_user($user_id) { // ... }
Conclusion
Variables are the foundation of any PHP application, allowing you to store and manipulate data throughout your code. Understanding how to properly create, name, and use variables will significantly improve your PHP coding skills.
As you continue your PHP journey, practice using variables in different contexts, and pay attention to scope and type handling. This knowledge will form the building blocks for more advanced PHP concepts like arrays, objects, and functions.
Remember, clean, well-named variables make your code more readable and maintainable—not just for others but for your future self as well!
Did you find this guide helpful? Do you have additional questions about PHP variables? Let us know in the comments below!