Introduction to Variables in PHP
By Stephen Bucaro
Computer programs usually work with some form of data. Data can be a number, a text
character or a string of text characters, the digital representation of a color, or
an array or matrix containing any of the above types of data.
Data is stored in memory. While a program is running, data is usually stored in RAM.
When a program is not running, data is stored on a magnetic disk or on a solid state
storage device. A program can also write data to a file, and extract data from a file.
Every piece of data has an address in memory. In some programming languages you might
actually access data by its address in memory, but in most programming languages,
a piece of data's memory address is referenced by a name that you assign to it in
the program code.
The defining feature of a variable is that its value can be changed during program
execution. Another form of data used by programs is constants. After you define a
constant's value in program code, that value cannot be changed during program execution.
I'll discus constants in a future article, in this article I'll focus on variables.
PHP supports eight types of variables
integer | A number without a decimal point. Includes negative numbers |
float | A number with a decimal point |
string | A character or characters |
boolean | Has two values TRUE or FALSE |
array | Holds multiple values of the same type |
object | A special data structure |
resource | A special kind of data used for interacting with databases |
NULL | A is not initialized as far as type or value |
Rules for PHP Variable Names
Variable names in PHP must follow these rules:
• Must start with a $ (dollar sign)
• Can contain letters, numbers, or underscores (_)
• The first letter after the $ cannot be a number
• Variable names are case sensitive
Variables can be Defined, Assigned, Manipulated, and Displayed
Shown below is a basic example of the use of PHP variables.
<?php
$a = 2;
$b = 3;
$c = $a + $b;
print $c;
?>
The first line of code defines a variable named $a and assigns it a value of 2.
The second line defines a variable named $b and assigns it a value of 3. In the
third line, the value of $a and $b are added together and the result is assigned
to a variable named $c. In the last line the print method is used to display
the value stored in $c.
Shown below is another example of the use of PHP variables.
<?php
$a = "Hello ";
$b = " There";
$c = $a . $b;
print $c;
?>
The first line of code defines a variable named $a and assigns it the character
string "Hello". The second line defines a variable named $b and assigns it the character
string " There". In the third line, the strings in $a and $b are concatenated
and then assigned to a variable named $c. In the last line the print method is
used to display the value stored in $c.
|