Expressions, Operators, and Variable Assignment

We've already described simple examples of assignment, in which a variable is assigned the value of an expression using an equals sign. Most numeric assignments and expressions that work in other high-level languages also work in PHP. Here are some examples:

Assign a value to a variable:

$var = 1;

Sum integers to produce an integer:

$var = 4 + 7;

Subtraction, multiplication, and division that might have a result that is a float or an integer, depending on the initial value of $var:

$var = (($var - 5) * 2) / 3;

These all add 1 to $var:

$var = $var + 1;
$var += 1;

And these all subtract 1 from $var:

$var = $var - 1;
$var -= 1;

Multiply to double a value:

$var = $var * 2;
$var *= 2;

Halve a value:

$var = $var / 2;
$var /= 2;

These work with float types too:

$var = 123.45 * 28.2;

There are many mathematical functions available in the math library of PHP for more complex tasks. We introduce some of these in next pages.

String assignments and expressions are similar:

Assign a string value to a variable:

$var = "test string";

Concatenate two strings together to produce "test string":

$var = "test" . " string";

Add a string to the end of another to produce "test string":

$var = "test";
$var = $var . " string";

Here is a shortcut to add a string to the end of another:

$var .= " test";