Almost everything you want to do in a PHP script is going to
involve moving some information around or otherwise manipulating it. Much
of this information will be held in variables. It is therefore a good idea
for us to take a quick look at what they are and the basic rules for their use.
Variables hold one or another "type" of information. PHP
is "loosely typed," meaning that the type of information to be held in a
particular variable can change on the fly. JavaScript is that way too, so
maybe you’re already familiar with loose types. Changing on the fly means
that if you start with a variable holding numerical data and use it in
calculations, for example, and then write an instruction to put text into it,
PHP will then consider it to be a text variable.
Here are the main data types used in PHP:
|
whole numbers |
An array needs a few words at this point. A simple example
of an array would be a string array called $month. There could be twelve
in the set and they could have the values January, February etc. To
reference the first of the set we use an index value thus:
$month(1)
In our example this would refer to array element with a value
of:
January
The index could also be a variable, thus:
$monthnum = 2;
echo $month($monthnum);
Assuming the array had been defined with the values descried in
our example, this would echo:
February
You’ve probably heard of type casting, but maybe not the kind
I’m thinking of here! This has nothing to do with thespian arts – type
casting in PHP means telling PHP to treat a variable of one type as if it was
another (without actually changing its type.) It doesn’t really matter
right here why you’d want to do that – it’ll become clearer later. For
now, just take a look at this example:
$quantity = 0;
$amount = (double)$quantity;
$quantity is set up as an integer with a value of zero.
The next line treats $quantity as a double type and assigns its value to
$amount. $amount is now a double with a value of zero and $quantity is
still an integer with a value of zero.
In PHP you can even use a variable as the name of a variable.
Take a look at this:
$varname = ‘quantity’;
$$varname = 5;
The second line uses the $varname variable in the name of the
variable being assigned the value of 5. Consequently the variable
$quantity is assigned the value 5. It does exactly the same thing as:
$quantity = 5;
This neat little trick hints at some of the power hidden in PHP.
The usefulness of this trick will become apparent when we do some processing in
loops later on.