In this tutorial you will learn about the PHP Variable and its application with practical example.
Variable is a identified or name that used to store a value. Variables are used for storing values such as numeric values, characters, character strings, or memory addresses so that they can be used in any part of the program.
Guideline for variable in PHP:
- Variables name must start with a letter or underscore “_”.
- Variables in PHP are represented by a dollar sign followed by the name of the variable.
- Variable name can only contain alpha-numeric characters and underscores.
- Spaces are not allowed in variable name.
- PHP variable name is case-sensitive
- PHP is a loosely type language
Declaring PHP variables:
1 2 |
//Syntax for declaring variable $variable_name = Value; |
1 2 3 4 5 6 7 |
<?php $abc = 'test'; //valid $Abc = 'test'; //valid $9xyz = 'test'; //invalid; starts with a number $_xyz = 'test'; //valid; starts with an underscore $_9xyz = 'test'; //valid ?> |
PHP is a loosely type language
In language such as C, C++ and Java the programmer must declare the name and type of the variable before use it. In PHP the type of the variable does not need to be declared before use it, because types are associated with values rather than variables. As a result a variable can change the type of its value as much as we want.
PHP variable variables
if you want the name your variable is a variable itself? In PHP, you have Variable Variables, so you may assign a variable to another variable.
1 2 3 4 5 6 7 |
<?php $v='v1'; echo $v; // prints v1 $$v = 'v2'; echo $$v; // prints v2 echo $v1; // prints v2 ?> |