PHP Variables
PHP Variables
PHP Variables store values. We can use variables in a PHP program or manipulate them later. PHP is a loosely typed scripting language, meaning we do not have to tell which data type the variable will hold.
Syntax
Variables in PHP are declared using the $ symbol.
The general syntax to declare a PHP variable is as follows:
$php_variable_name = value;
A variable in PHP starts with a dollar ($) sign. php_variable_name is the name of the variable that holds the value. We use an assignment operator to store the value in the variable.
PHP is a dynamically typed language, meaning you don’t need to declare a variable’s type beforehand. The type is determined by the value assigned to it.
Naming Rules
Some variable naming rules are as follows:
- A variable name can start with a letter or an underscore “_”
- A variable name should not contain whitespaces.
- A variable name can be comprised of alpha-numeric characters and underscores. (a-z, A-Z, 0-9, or _)
- Variable names are case-sensitive. That means the following variable names are different
$Foo and $foo.
You should avoid using PHP-reserved keywords or function names as variable names to prevent conflicts. For example, if, else, echo, function, and other reserved words should not be used as variable names.
Tip
When we type the $ sign in the program, the IDE editor prompts with PHP Platform variables. We can pick the required variable name automatically without typing the whole variable name.
Variable naming rules in programming are important.
Readability: Clear and descriptive variable names make your code easier to read and understand. Good names convey the variable’s purpose, helping others understand what the code is doing. Naming conventions help maintain consistency across the codebase.
Maintainability: Code is often updated or modified over time. Using meaningful names reduces the risk of mistakes and makes it easier to maintain and refactor the code.
Example
In the following statement, we will assign the variable “number” a value of 79
$number = 79;
Note that variable names are case-sensitive in PHP. $NUMBER and $number are two different variables in PHP.
PHP Tutorials
PHP Tutorials on this website:
More Information on PHP