PHP Variables

In Programming Languages variables are used for storing values such as numeric values, characters, character strings etc. Basically a variable acts like a container for string information, which can be accessed by using the variable name in all over the script or program code depending on its scope.

In PHP, a variable is declared using the $ sign followed by variable name and the assignment ( = ) operator is used to assign value to a variable. The basic syntax would be :
 $variable_name = value;
Where veriable_name is name of the variable and value is the value assigned to that variable.

Example :

  $num = 1000;
  $float = 25.80;
  $str = "Hello world";

  echo $num . "<br/>";
  echo $float . "<br/>";
  echo $str . "<br/>";

Output :

Hello world

Unlike other programming languages PHP is a loosely typed language, it automatically converts the variable to the  correct data type, depending on its value. As we can see at the above script the variable $num holds the numerical value, $float holds the floating point value, and $str holds the string value. The php variable names are case sensitive, means the variable name $num is different then variable $Num, $nUm, $NUM.

Rules for naming a variable :

There are certains rules which needs to follow, when naming a variable PHP :

  • All variables in PHP start with a $(dollor) sign followed by the name of the variable.
  • A variable name must start with a letter or the underscore character ( _ ).
  • A variable name can not start with a number.
  • A variable name in PHP can only contain alpha-numeric characters (A-Z, a-z, 0-9) and underscore ( _ ).
  • A variable name can not contain spaces.