When you learn PHP, one of the first points to grasp is how to use variables. Variables can be of different datatypes> and you must respect the datatype of the variable you are using. In this brief PHP tutorial, we first look at variables as a generic and then at each PHP datatype in turn.
A PHP variable, like any other programming language, is a container for a value. By definition, a variable holds varying values. In PHP, variables are always indicated by a prepended dollar sign ('$'). So instead of referencing the variables 'foo' or 'bar' by just their names, we reference them as '$foo' and '$bar', respectively. We then assign value to that variable using an equals sign ('='):
$foo = 27;A variable name is just a handle for a specific location in the PHP stack (i.e., RAM). If that location can hold the value 27, it can also hold the integers 36 or 81.
$bar = 3;
In PHP, we can also assign values by computation. So, instead of a value of 81, we can assign the value as follows:
$foobar = $foo * $bar;The value of $foobar then is the result of multiplying $foo by $bar, or 81.
To indicate that a value is a string as opposed to an integer, put it in quotes.
$abra = "Hocus";You can then concatenate strings in PHP using the dot operator (aka, period or full stop).
$cadabra = "Pocus";
$sna = "Situation Normal: All ";You can use the same method to concatenate integers and strings:
$fu = "Fouled Up.";
$snafu = $sna.$fu;
$foo = 12;The resulting value of $foobar is "12 Days of Christmas". You will note the use of a blank space in between the two dots when assigning the value to $foobar. This is merely to introduce a space between the two values. If we wanted to, as we did in the preceding example, we could include the space as part of one of the values.
$bar = "Days of Christmas";
$foobar = $foo." ".$bar;
Understanding the basics of working with PHP variables, you should further understand PHP datatypes and how they impact on your programming. See the complementary PHP tutorial to this one, "PHP Datatypes".
|Install PHP||Basic PHP Configuration||PHP Configuration In-Depth|
|Learn PHP||PHP in HTML||PHP Keywords|
|PHP Expressions||PHP Variables||PHP Constants|
|Defined Constants||Constants Characteristics||PHP Datatypes|
|PHP Syntax Basics||PHP Loops|
|Install Apache||Basic Configuration||Apache In-Depth|
|Recommend Web Hosting||Customising Apache||PHP Hosting|
|Install MySQL||Basic MySQL Configuration||MySQL Configuration In-Depth|