Variables in PHP

Variables in PHP, much like in any programming language, are named pockets in which pieces of data are stored. All variable names in PHP must begin with a "$" character, followed by a string made up of letters, numbers, and underscores.

Caution

 

Variable names are case sensitive in PHP. For example, $varname and $VarName represent two distinct variables. Take care to enter the names of variables in the correct case.

 

We can assign values to variables in PHP without declaring the variables beforehand:

$score = 71;
$player = 'Harry Scott';

 

Variables can take a number of data types, including strings, integers, floats, and Boolean (true or false). When a variable is assigned a value, such as in the preceding examples, PHP assigns a data type automatically.

Numbers

All the basic mathematical operators are available in PHP, as shown in the following examples:

$answer = 13 + 4;
$answer = 13 * 4;
$answer = 13 / 4;
$answer = 13 - 4;

 

You can also calculate the modulus, for which we use the % character:

$answer = 13 % 4;

 

Strings

In PHP you enclose strings within single or double quotes:

$mystring = "The quick brown fox";

 

Strings may be concatenated using the period character:

$newstring = " jumped over the lazy dog";
$concat = $mystring.$newstring;

 

Tip

 

PHP offers the date() command, which allows you to get the server time and date and format it to your liking; for example, the line

echo date('D F Y H:I');

outputs the current date in a form similar to Fri 16 December 2005 11:36.

 

 

Arrays

PHP also supports arrays. An array is a variable that can contain a set of values rather than just one. Here's a PHP array containing some of the days of the week:

$daynames = array("Monday","Tuesday","Wednesday","Thursday","Friday");

 

The items in an array are referenced by a key, which is an integer starting at zero and incrementing for each item in the array. The following line outputs Thursday to an HTML page:

echo $daynames[3];

 

Note that, because the index value begins at zero, the preceding statement actually echoes the fourth element of the array.

This type of array is known as a numeric array, but you may also use associative arrays. In this case, the key value of each element is not numeric but instead is a string of your choosing. The syntax to declare such an array and assign values to it is slightly different:

$lunch = array("Susan" => "Chicken", "Matthew" => "Beef", "Louise" => "Salmon");

 

You can now select the elements of such an array using the key value:

echo $lunch["Louise"];

 

This command would output the word Salmon to our page.