PHP Tutorial: Variables
WEBINAR: On-demand webcast
How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >
Here are the main data types used in PHP:
In our example this would refer to array element with a value of:
The index could also be a variable, thus:
$monthnum = 2;
Assuming the array had been defined with the values descried in our example, this would echo:
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.