Search code examples
phpauto-increment

Autoincrementing strings


I'm trying to build a hierarquical list of categories, like this:

1 Category
  1.1 Children
  1.2 Children
      1.2.1 Children

Here's my code:

$a = "1.1";
echo ++$a; // 2.1

$b = "1.1.1";
echo ++$b; // 1.1.2

Why $a increments to 2.1 instead of 1.2 like $b?


Solution

  • "1.1" parses to the float value 1.1, and anyone can tell you that 1.1 + 1 = 2.1

    However, "1.1.1" can't be parsed into a number, so it is treated as a string. PHP supports ++ for strings in different ways in an attempt to be useful, however this is only really successful for letters (A through Z, then AA, AB...).