PHP Variables
In PHP variables function as storage containers for data types like numbers, strings, arrays and objects. Programming with PHP variables lets you reuse existing data while modifying it throughout your application.

Rules for Declaring PHP Variables
- In PHP, any variable begins with a $ symbol which precedes the variable name.
- The name of a PHP variable must start with a letter or the underscore character (_.
- It cannot start with a number.
- Variable names are case-sensitive ($name ≠ $Name).
- PHP does not require you to specify variable data types because of its dynamic typing system.
Example
<?php $name = "Alice"; $age = 25; $price = 19.99; $isAdmin = true; echo "Name: $name, Age: $age, Price: $price, Admin: $isAdmin"; ?>
Variable Types
| Type | Example |
|---|---|
| String | $name = "Alice"; |
| Integer | $age = 30; |
| Float | $price = 45.99; |
| Boolean | $isAdmin = true; |
| Array | $fruits = ["apple", "banana"]; |
| Object | $user = new User(); |
| NULL | $value = null; |
Variable Interpolation
Double-quoted strings allow you to directly embed PHP variables.
echo "Hello, $name"; // Works echo 'Hello, $name'; // Doesn't interpolate
Variable Scope
Global Scope
A variable declared outside of a function remains inaccessible inside the function unless it is marked as global.
$siteName = "MySite";
function showSite() {
global $siteName;
echo $siteName;
}
Local Scope
A variable declared within a function remains accessible exclusively to that function.
function greet() {
$message = "Hello!";
echo $message;
}
Static Scope
Preserves variable value between function calls.
function counter() {
static $count = 0;
$count++;
echo $count;
}
isset() and unset()
isset($name); // Checks if variable is set unset($name); // Destroys the variable
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com