Rules for Naming The Variable In Php | PHP Variables

Variables in a programming language are very important to program. The variables are the temporary spaces in the memory where we put the data. You can call them as data containers. They give the programmer and the program code flexibility in the use of values. For example if you want to add two numbers in PHP without the use of PHP variables you may write it as

<?php

echo (2 + 3);

?>

The answer is very simple 5 in the above code. But if you want to add 5 and 6 you have to write the program again. Or you have to make changes directly in the code. But if you use variables instead it will be very helpful and easy to add other numbers.

It is very easy to make PHP variables. You have to just put a “$” (dollar) sign before the name of the variable. PHP variable name can comprise letters (A-Z a-z), numbers (0-9) or the underscore ( _ ). Keep in mind that you can’t use spaces or special characters like @, % etc. The PHP variables start with an underscore ( _ ) or a character (A-Z a-z). Avoid very long variable names. You can use the Hungarian Notation for you variables. Or you can use the underscore ( _ ) to separate the words in a variable name. Following are some PHP variables names examples:

$my_var;

$myVar;

$_myVar;

$_myVar123;

$_123myVar;

$MY_var;

You have to be very careful in variable declaration because in PHP every statement is ended with a semicolon “;”. You have to tell the code parser that it is the end of line otherwise the result will not be good for you.

In PHP you can declare a variable and you don’t have to tell that what will be stored in the variable. As in C or C++ you have to tell that in this variable we are going to store a string or an int. So it means that you can give a string value and an int or something else later in the code.

The PHP variables are assigned values with the single equal sign (=). The double equal sign (==) is used for the comparison. So you have to be careful in using the equal sign.

The string variables are used in single or double quotes. You can use single and double quotes for strings. The numbers are used as they are. We will discuss the data types later.

Comments