How to Declare a Variable in PHP
In PHP, variables are used to store data that can be used and manipulated throughout your script. This article explains how to declare a variable in PHP, covering the basic syntax, naming rules, and how PHP handles different data types, complete with practical code examples.
The Basic Syntax
In PHP, a variable is declared using a dollar sign ($)
followed by the variable name. The assignment operator (=)
is used to assign a value to the variable.
$variable_name = value;Here is a basic example of declaring a variable and assigning it a string value:
$greeting = "Hello, World!";In this example, $greeting is the variable name, and
"Hello, World!" is the value assigned to it.
Rules for Naming PHP Variables
When declaring variables in PHP, you must follow these specific naming conventions:
- Start with a dollar sign: All variables must begin
with the
$symbol. - First character after
$: The variable name must start with a letter (A-z) or an underscore (_). It cannot start with a number. - Allowed characters: Variable names can only contain
alphanumeric characters and underscores (A-z, 0-9, and
_). - Case-sensitivity: Variable names are
case-sensitive. For example,
$ageand$AGEare treated as two completely different variables.
Correct Examples:
$myVariable = "John";
$_temp = 98.6;
$user_age = 25;
$var1 = "test";Incorrect Examples:
$1var = "test"; // Invalid: Starts with a number
$my-var = "test"; // Invalid: Contains a hyphenPHP is a Loosely Typed Language
Unlike many other programming languages, PHP is loosely typed. This means you do not need to declare the data type of a variable before using it. PHP automatically converts the variable to the correct data type based on the value you assign to it.
Here are examples of declaring different data types in PHP:
$txt = "Hello"; // String
$num = 15; // Integer
$pi = 3.14159; // Float (floating point number)
$is_active = true; // BooleanVariable Re-assignment
You can change the value of a variable at any point in your script by simply assigning it a new value. The new value will overwrite the previous one.
$color = "red";
$color = "blue"; // The value is now "blue"