Quakenet/#php Tutorial

Note: If you opened this page from an external URL pay attention that all chapters are linked together. Be sure you also read all prior chapters of this tutorial, otherwise you will miss relevant content explained before.

Abbreviations

  1. Assignment operator
  2. In-/decrement

1. Assignment operator

There are some assignment operators in php which changes the content of a variable depending of its current content.

<?php
$var 
5;

$var $var 10;

$var += 10;
?>

The second adds the value of the variable and a constant value together and saves it in the variable. The third statements instead adds the value right on the current value of the variable and saves it. You must not place any whitespaces between + and = as this is a predefined operator.

<?php
$var 
5;

$var += 10;  // correct
$var + = 10// wrong, results in an parse error
?>

This abbreviation can be used for every number calculation operators, even with / and %. However you shouldn't divide by 0 (of course).

<?php
$var 
20;

$var +=4// $var == 24
$var *=4// $var == 96
$var -=4// $var == 92
$var /=4// $var == 23
$var %=4// $var == 3  (23/4 = 5, remaining 3)

?>

This abbreviation can also be used for the concat operator . to append very fast new text to a variable.

<?php
$x 
5;

$string  "Hi \n";
$string .= "You can add new text easily.\n";
$string .= 'test';
$string .= 'The variable have the value '.$x."\n";
?>

In the last line the expression on the right gets calculated first and then is appended to the variable.

2. In-/decrement

Often you want to change a variable by increasing or decreasing the value by 1. For this reason there are increment and decrement operators in php, similar to C.

<?php
$name 
10;

$name++;    // increase by 1

echo $name// outputs 11
?>

Thats for increment, for decrement use the -- operator.

<?php
$name 
10;

$name--;    // decrease by 1

echo $name// outputs 9
?>

There aren't such operators for multiplication of division, these wouldn't make any sense. These increment and decrement operators are often used for for loops.

Questions about the chapter

No questions

Back to Next to
Copyright © to the OPs of #php/QuakeNet Valid XHTML 1.0 Strict Valid CSS!