Like other programming and / or scripting languages, in PHP too variables are used for storing values, such as numbers, strings or arrays, that can be used and reused in PHP again and again.
PHP is a loosely typed language. This means that, when declaring a variable, we do not have to tell PHP which data type the variable is. PHP automatically converts the variable to the correct
data type, depending on the value being assigned to it. This on the contrary to a strongly typed programming language, where we have to declare (define) the type of the variable when declaring
PHP internally uses the following data types to store variables:
• float or double
Declaring variables in PHP
All variable names (identifiers) in PHP start with a $ sign symbol. The correct way of setting a variable in PHP is as under:
$var_name = value;
If we forget to add the $ sign at the beginning of the variable name, the code will not work. New PHP programmers often forget this, so be careful.
Consider the following PHP script:
$txt = "Hello World!";
$number = 16;
The above code creates one string variable named $txt and one integer variable named $number. The string, like most of the languages, has to be enclosed in quotes.
Points to Remember
- In PHP a variable does not need to be declared before being set.
- In PHP variable names are case-sensitive.
- A variable name must start with a letter or an underscore "_".
- A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ).
- A variable name can not contain spaces. If a variable name contains more than one word, you could seperate it with an underscore ($my_var) or by capitalizing the second and each
subsequent word ($myVar).
- PHP does not support unsigned integers.
- There is no integer division operator in PHP. 1/2 yields the float 0.5, for example.
- Un-initialized variables have a default value of their type i.e. FALSE, zero, empty string or an empty array.
A constant is an identifier (name) for a simple value that cannot change during the execution of the script. By convention, constant identifiers are always uppercased. The name of a constant
follows the same rules as any label in PHP, except that it does not start with the $ sign. We can define and use a PHP constant as under:
define ("FAV", "PHP");
echo FAV; // outputs PHP