WHAT ARE VARIABLES AND HOW TO USE THEM IN PHP
Variables are sort of like containers that hold information. With PHP, you first have to name your variable and then you can store a value in it. That variable now contains that value. For example:
$toys=25;
The variable $toys now has a value of 25 stored in it.
Another example:
$name="John";
The variable $name has a value of John stored in it.
If you do this to the same variable in the same script:
$name="Fred";
The variable $name ceases to hold value of John but now holds value of Fred instead.
You probably have noticed the $ in front of the variable name. This dollar sign is PHP’ s way of recognizing a variable and all variables declared in PHP must have this dollar sign.
Some important points to consider with variables:
- Variables must start with a $ sign.
- Variable names are case sensitive ie. $NAME and $name are two different variables.
- Variables can be any length.
- Variables can only start with an underscore or letter and not numbers.
- Only letters, numbers or underscores are allowed for variable names. No other special characters are allowed.
- The value of a variable that is only numbers do not need quotes but must terminate at line end with semi-colon.
- The value of a variable that is a sting do need quotes and must also terminate at line end with semi-colon.
- The value of a variable that is another variable do not need quotes and must also terminate at line end with semi-colon.
Variables can take a value of numbers or strings but can also take on the value of another variable. Example:
$car="Porsche";
$favouritecar=$car;
Now both $car and $favouritecar has a value of Porsche.
Echoing variables
When you echo a variable, the value is outputted. Example:
<?
$car="Porsche";
echo $car;
?>
This will output Porsche.
|