What Are PHP Variables?
A variable in PHP is used to store data (such as a number, string, or array) and can be used later in the script. Variables in PHP are dynamic, meaning you don’t need to declare their type.
Rules for PHP Variables
✔ Must start with a $ sign (e.g., $name
).
✔ Must begin with a letter or underscore (_), not a number.
✔ Can contain letters, numbers, and underscores.
✔ Are case-sensitive ($name
and $Name
are different).
✔ Cannot contain spaces (use underscores or camelCase).
Declaring and Assigning Variables
<?php
$name = "John"; // String
$age = 25; // Integer
$price = 99.99; // Float
$isActive = true; // Boolean
echo "Name: " . $name . "<br>";
echo "Age: " . $age;
?>
Explanation:
$name
stores a string.$age
stores an integer.$price
stores a float.$isActive
stores a boolean (true
or false
)..
is used to concatenate (join) strings.<br>
adds a line break in HTML output.PHP variables have three main scopes:
Local Variables (Inside a Function)
<?php
function myFunction() {
$x = 10; // Local variable
echo $x;
}
myFunction();
// echo $x; // This would cause an error because $x is not accessible outside the function.
?>
Global Variables (Outside Functions)
<?php
$y = 20; // Global variable
function showValue() {
global $y; // Using global keyword
echo $y;
}
showValue();
?>
$_GLOBAL
, $_POST
, $_GET
, etc.)Super global variables are accessible from anywhere in the script.
You can change the value of a variable anytime.
<?php
$color = "red";
echo $color; // red
$color = "blue"; // Reassigning new value
echo $color; // blue
?>
define()
) cannot be changed after declaration.<?php
define("SITE_NAME", "My Website");
echo SITE_NAME;
?>
PHP variables store different data types and can be reassigned. They follow specific naming rules and have local, global, and super global scopes.