In PHP, a variable is declared using a $ sign followed by the variable name. Here, some important points to know about variables:
- As PHP is a loosely typed language, we do not need to declare the data types of the variables. It automatically analyses the values and makes conversions to its correct data type.
- After declaring a variable, it can be reused throughout the code.
- Assignment Operator (=) is used to assign the value to a variable.
Syntax of declaring a variable in PHP is given below:
$variablename = value;
Rules for declaring PHP variable:
- A variable must start with a dollar ($) sign, followed by the variable name.
- It can only contain alpha-numeric characters and underscore (A-z, 0-9, _).
- A variable name must start with a letter or underscore (_) character.
- A PHP variable name cannot contain spaces.
- One thing to be kept in mind is that the variable name cannot start with a number or special symbols.
- PHP variables are case-sensitive, so $name and $NAME both are treated as different variables.
PHP has a total of eight data types which we use to construct our variables −
- Integers − are whole numbers, without a decimal point, like 4195.
- Doubles − are floating-point numbers, like 3.14159 or 49.1.
- Booleans − have only two possible values either true or false.
- NULL − is a special type that only has one value: NULL.
- Strings − are sequences of characters, like ‘PHP supports string operations.’
- Arrays − are named and indexed collections of other values.
- Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
- Resources − are special variables that hold references to resources external to PHP (such as database connections).