Learn How To Define Variable In PHP With Example

Learn How To Define Variable In PHP With Example

Variable In PHP play an important role in every programing language. Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script.

All variable in PHP start with a $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name in PHP can only contain alphanumeric characters and underscores ( A-z , 0-9 , and _ ).

Here’re some important things to know about variables:

  1. In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
  2. After declaring a variable it can be reused throughout the code.
  3. The assignment operator (=) used to assign value to a variable.
  4. All variables in PHP are denoted with a leading dollar sign ($).
  5. The value of a variable is the value of its most recent assignment.
  6. Variables can, but do not need, to be declared before assignment.
  7. Variables used before they are assigned have default values.
  8. A variable name cannot start with a number.
  9. A variable name cannot contain spaces.
  10. PHP does a good job of automatically converting types from one to another when necessary.

Note:Variable name in PHP are case sensitive, it means $A and $a are two different variables. So that, be careful while defining variable names.

In PHP variable can be declared as: $var_name = value;

Variable In PHP With Example

In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. We’re displayed the variables values in the browser using the echo statement.