In this tutorial, you will learn what is PHP variable and how to use it.
Variables are nothing but the name of the memory location. Variables store different kinds of data like numeric and non-numeric data. Values in the PHP variables can be changed during the course of the script. Below are some of the important features of PHP variables:
- PHP is a loosely typed language. Therefore there is no need for declaring variables before assigning. PHP automatically converts the variable to its correct type depending on its value.
- PHP variables can be used throughout the program after declaring it.
- The assignment operator (=) is used to assign a value to the variable.
PHP Variable Syntax
Syntax of declaring the variable in PHP is as below:
PHP Variable Example
<?php // Declaring variables $num = 20; $txt = "Hello World!"; // Displaying variables value echo $num; echo '<br>'; echo $txt; ?>
In the above example, we have created two variables and assigned them with number and string values. After that, we have displayed the variable values using the echo statement. PHP echo statement is used to get output data to the browsers. We have already learned about it in our previous tutorial.
Rules for PHP Variables
Below are rules for defining PHP variable:
- PHP variable names start with $ and followed by variable names.
- All the variable name in PHP only contain alpha-numeric characters and underscore (A-Z, a-z, 0-9 and _ )
- A variable in PHP must start with a letter or underscore.
- A variable name cannot start with numbers.
- A variable cannot contain space.
Note: PHP variables are case-sensitive. That means $var and $VAR are two different variables.