-1

I have the following variable defined in a PHP document I am working with, and I'm unsure what it means.

The PHP

$page -= 1;

The part I am unsure of is the -=

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
stefmikhail
  • 6,877
  • 13
  • 47
  • 61

4 Answers4

7

It's a shorthand to save typing. It's effect is idential to

$page = $page - 1;
Peder Klingenberg
  • 37,937
  • 1
  • 20
  • 23
3

The -= operator is shorthand for subtracting a value from the variable:

$x -= 1;
$x = $x - 1;

Here's some of the other ones:

  1. $x += 1; ($x = $x + 1)
  2. $x -= 1; ($x = $x - 1)
  3. $x *= 1; ($x = $x * 1)
  4. $x /= 1; ($x = $x / 1)
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Very very helpful. Thanks so much! I commented on the answer above. Think you can shed some light on that? – stefmikhail Aug 21 '11 at 18:28
  • 1
    `$page` is only defined once. If I do `x = 1` and `x = 2`, `x` is equal to `2` because that is the last value I told `x` to be. BTW, `x = 1` and `1 = x` are not the same thing, so `$cur_page = $page;` is setting `$cur_page`, not `$page`. – Blender Aug 21 '11 at 18:30
  • Thanks for the clarification. Also, your answer was thorough and will be quite helpful in my future endeavours with PHP. – stefmikhail Aug 21 '11 at 18:42
  • What would `"page="+page` mean? – stefmikhail Aug 21 '11 at 21:55
1

The -= operator is a combination arithmetic and assignment operator. It subtracts 1 then reassigns it to $page.

  • So in my document, the following variables are defined: `$page = $_GET['page']; $cur_page = $page; $page -= 1;` How can `$page` be defined as three different things? – stefmikhail Aug 21 '11 at 18:26
  • 2
    It's defined once (the first time it occurs) and then operations are performed that modify it's value. So if `$_GET['page']` equals 10, then `$page` will equal `10` as well after `$page = $_GET['page'];`, then `$cur_page` will also be assigned a value of `10` and finally value of `$page` will be reduced to `9` after `$page -= 1;` – Mchl Aug 21 '11 at 18:31
  • @Mchl One question. I'm guessing the reason the code isn't just `$page -= $_GET['page']` is for the `$cur_page` variable to be defined as the current page, correct? I suppose I could also use a different variable, i.e.. `$page_minus_one = $page - 1`, am I correct? – stefmikhail Aug 21 '11 at 18:46
1

It's the same as $page = $page - 1, $page-- or --$page, it's used to decrement the value of the variable.

Mark Tomlin
  • 8,593
  • 11
  • 57
  • 72
  • 1
    Careful about `$page--` and `--$page`. They're almost, but not quite the same. – Mchl Aug 21 '11 at 18:32
  • 1
    Yes, one get's decremented before the copy, when happens after, but the statements by themselves are effectively the same when used on a line all by themselves. – Mark Tomlin Aug 21 '11 at 18:34