PHP—Manipulating Variables

Once you have information stored in a variable, what are you going to do with it? As we have seen, you can echo it to a web page. You also can manipulate the information with operators. Here are examples of mathematical operations in PHP:


$b = $a + 3;
$c = $a - 5;
$b = $b * 5;
$d = $b / $c;

In addition to the basic assignment operator (=), there is a string-concatenation operator (.=) and combination assignment/mathematical operators. Here are some examples:


$string1 = "super";
$string2 = "star";
$string1 .= $string2; // $string 1 now equals "superstar"

$name = "Stephen";
$name .= " Crampton"; // note the space; name now equals "Stephen Crampton"

$c = 5;
$c += 1; // result is $c + 2, or 6

$c -= -1; // result is $c - (- 1), or 7

$x = 5;
$x *= $c; // result is $x * $c, or 35

$y = 70;
$y /= $x // result is $y / $x, or 2

There also are simple increment/decrement operators, which are essentially shorthand ways of adding or subtracting one from a number:


$a = 5;
$a++; // $a has been incremented by 1, and now equals 6

$a--; // $a has been decremented by 1, and now equals 5

$b = 5 * $a++; // Note that the incrementing happens after the evaluation:
               // First, $b is calculated to be 25.  Then, $a is
               // incremented to become 6

//
// If you want $a to be incremented first, put the ++ in front of it
// as follows:
$b = 5 * ++$a; // $a incremented to 7; $b becomes 35

$c = 100;
$c -= ++$b + $a++; // $b becomes 36; $c is calculated to be
                   // 100 - ( 36 + 7 ); finally, $a becomes 8

Next (Control Statements)