PHP variables, How to define a variable in PHP?

Rate this post

Variables are used to store data, like text, numbers, etc.

How to define a variable in PHP?

In PHP a variable starts with the $ sign, followed by the name of the variable.

Naming Variables

A variable consists of two parts: the variable’s name and the variable’s value.

Rules you must follow when naming a variable in PHP

  • Variable names begin with a dollar sign $
  • The first character after the dollar sign must be a letter or an underscore. The remaining characters in the name may be letters, numbers, or underscores without a fixed limit
  • Careful! Variable names are case sensitive so, $Variable and $variable are two distinct variables

Creating Variables

Creating a variable in PHP is known as declaring it.
When PHP first sees a variable’s name in a script, it automatically creates the variable at that point.
Many programming languages prevent from using a variable without first declaring it, but in PHP the variable does not need to be declared before assigned a value to it, because PHP automatically converts the variable to the correct data type, depending on its value.
For example, the variable $number could hold the value 7 and the string “seven” within the
same scope. In other languages, such as C or Java, you must declare the type of a variable before assigning a value to it, and the value must be of the specified type.

Anyway, when declaring a variable in PHP, it’s a good practice to assign a value to it at the same time. This is
known as initializing a variable.
$my_variable = 5;

Because PHP is loosely typed is important to use primitive types checking functions, to check the type of a variable.

Primitive types checking functions in PHP

is_bool() Boolean One of the two special values true or false
is_integer() Integer A whole number
is_double() Double A floating point number (a number with a decimal point)
is_string() String Character data
is_object() Object An object
is_array() Array An array
is_resource() Resource A handle for identifying and working with external
resources such as databases or files
is_null() Null An unassigned value

Leave a Reply

Your email address will not be published. Required fields are marked *