24 August 2013

Recently I stumbled upon (or over - depending on the point of view) the increment and decrement operators, also know as ++ or --.

After dealing with with the + and + operators one might think: Whats the matter? ++$i is just a shorthand for $i = $i + 1, right?

Err … nope.

Just take a look at this

<?php
$i = 10;
echo '1) ++$i = '; var_dump(++$i);
$d = 9.9;
echo '2) ++$d = '; var_dump(++$d);
$s1 = "10";
echo '3) ++$s1 = '; var_dump(++$s1);
$s2 = "abcd";
echo '4) ++$s2 = '; var_dump(++$s2);
?>
1) ++$i = int(11)
2) ++$d = float(10.9)
3) ++$s1 = int(11)
4) ++$s2 = string(4) "abce"
  1. Ok
  2. Ok
  3. Yawn … just another implicit conversion, already had my share of these
  4. Wut?

Again some research is necessary. Obviously someone considered it cool to calculate with letters and digits directly. Actual rules for this are not quite obvious:

<?php
$s = "ab"; echo "++ $s = " . ++$s . "\n";
$s = "az"; echo "++ $s = " . ++$s . "\n";
$s = "zzz"; echo "++ $s = " . ++$s . "\n";
$s = "A00"; echo "++ $s = " . ++$s . "\n";
$s = "A99"; echo "++ $s = " . ++$s . "\n";
?>
++ ab = ac
++ az = ba
++ zzz = aaaa
++ A00 = A01
++ A99 = B00

I could go on like this, instead I just point to my reimplementation in Scala: PHP ++ in Scala. Actually I am not very proud of this chunk, so feel free to correct and/or optimize.

Now, what about the --? Just the other way round, right?

Nope.

<?php
$s = "abc";
var_dump(++$s);
var_dump(--$s);
?>
string(3) "abd"
string(3) "abd"

Yes, you see right: ++ does this funny think with string, -- does nothing.

And while we are at it: Here is another funny thing about the --. See what happens if you do an increment/decrement of an uninitialized variable:

<?php
var_dump(++$unknown1);
var_dump(--$unknown2);
?>

Notice: Undefined variable: unknown1 in - on line 2
int(1)

Notice: Undefined variable: unknown2 in - on line 3
NULL

Uhu … ++ of nothing is 1, while -- of nothing is NULL. I have to admit that this logic is beyond me.

So, what happens if we have all this kind of fun - 9049357 times to be exactly? Lets see what PHP has to say to this

<?php
$fun="fun";
for($i = 0; $i < 9049357; $i++)
    $fun++;
echo $fun;
?>
sucks

Yeah … right.