PHP Variables

Variables are used to store simple values, complex data, or HTML code to use later in the program. Unlike many other languages, the variable does need to be declared explicitly before assigning a value to it. Once assigned a value, you can use a variable throughout your script.

While declaring or assigning a variable, you do not have to mention the variable's data type, as it is not predetermined. PHP interpreter automatically determines variable data types in runtime by evaluating their value.

Since PHP is based on the PERL language, it identifies a variable with a leading $ symbol. The leading dollar sign($) denotes a variable in PHP. The assignment operator(=) is used to assign a value to a variable. The following example declares and assigns a variable $var_name with the value Hello World.

			

<php
// Must begin with $sign
$var_name = “Hello World”;  
?>

				

A numeric character cannot be used to begin a variable name. However, alphabets characters (i.e., A-Z, a-z) or underscores can be used to begin a variable name. A variable name must be made up out of a selection of alphanumeric characters and underscores. Variables are case sensitive $var_name, $VAR_Name and $Var_name are treated as same one. The following example depicts the proper usage of variable names.

			

<?php
$var_name = “Hello World”;    // Correct
$123 = “Hello World”;    // Wrong
$v123 = “Hello World”;    // Correct
$_123 = “Hello World”;    // Correct
$var_123 = “Hello World”;    // Correct
?>

				

The following example declares a string value, an integer, and a float value.

			

<?php
$var_str = "Hello World!";
$ var_num = 10;
$ var_float = 23.45;
?>

				

In PHP, when you name a variable, you have to be cautious that the variable name is case-sensitive.

			

<?php
$Movie = "The Batman";
echo "My Favourite movie is " . $Movie . "<br>";
echo "My Favourite movie is " . $MOVIE . "<br>";
echo "My Favourite movie is " . $movie . "<br>";
?>

				

Output:

My Favourite movie is The Batman My Favourite movie is My Favourite movie is