Stamoulohta
Stamoulohta

Reputation: 659

Decrement operator for strings bug in PHP?

There is an inconsistency in increment/decrement operator function regarding strings in -at least- my version of PHP. Here is what I mean:

php > echo phpversion();
7.4.11
php > $test = 'abc12';
php > // increment works as expected
php > echo(++$test);
abc13
php > echo(++$test);
abc14
php > echo(++$test);
abc15
php > // but decrement fails
php > echo(--$test);
abc15
php > echo(--$test);
abc15
php > echo(--$test);
abc15

Is this an expected behavior? Should I file a bug report or something? Do you know of a workaround?

edit: filed bug#80212

Upvotes: 1

Views: 259

Answers (2)

Álvaro González
Álvaro González

Reputation: 146450

That's the documented behaviour (emphasis mine):

PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl $a = 'Z'; $a++; turns $a into 'AA', while in C a = 'Z'; a++; turns a into '[' (ASCII value of 'Z' is 90, ASCII value of '[' is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII alphabets and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged.

Upvotes: 2

Stamoulohta
Stamoulohta

Reputation: 659

Here is what I finally went with:

function decrement($str) {
  $matches = preg_split('/(\d+)\z/', $str, -1, PREG_SPLIT_DELIM_CAPTURE);
  @--$matches[1];
  return implode($matches);
}

Wouldn't call it elegant but I'd call it functional.

Upvotes: 0

Related Questions