rfc:normalize_inc_dec

This is an old revision of the document!


PHP RFC: Normalize increment and decrement operators

Introduction

The current behaviour of increment and decrement operators is not very intuitive:

// booleans
$a = false; ++$a; // bool(false)
$a = true; --$a; // bool(true)
 
// null values
$a = null; --$a; // null
$a = null; ++$a; // int(1)
 
// empty strings
$a = ''; ++$a; // string(1) "1"
 
// non-numeric strings
$a = '12d9'; 
++$a; // string(4) "12e0"
++$a; // float(13)

Proposal

The proposal is either:

  1. Treat boolean and null types as a restricted type value and deprecate alphanumeric increment.
  2. Treat boolean and null types as an integer value and deprecate alphanumeric increment.
  3. No changes.

Option 1: Restricted type values

// booleans
$a = false; 
++$a; // bool(true)
++$a; // bool(true)
$a = true; 
--$a; // bool(false)
--$a; // bool(false)
 
// null values
$a = null; --$a; // null
$a = null; ++$a; // null
 
// empty strings
$a = ''; ++$a; // int(1)

Option 2: Integer values

// booleans
$a = false; 
++$a; // bool(true)
++$a; // int(2)
$a = true; 
--$a; // bool(false)
--$a; // int(-1)
 
// null values
$a = null; --$a; // int(-1)
$a = null; ++$a; // int(1)

Deprecating alphanumeric string increment

// non-numeric strings
$a = '12d9'; 
++$a; // string(4) "12e0" + Notice: String increment is deprecated, use str_inc() instead in php shell code on line 1
++$a; // float(13)

Additionally, it makes two new string functions available:

  • str_inc($str) - to perform the current string increments.
  • str_dec($str) - the string decrement.

Backward Incompatible Changes

With “option 1” the null value no longer increments to 1; this may lead to problems in for-loops with null values as the start argument.

Proposed PHP Version(s)

Next 5.x

Introduce a notice for the current string increment use case. This will help developers spot their usage more easily.

Next major

Removal of string increment using ++ and --.

Open Issues

None.

Unaffected PHP Functionality

The changes do not affect the following data types:

  • array
  • int
  • float
  • object
  • resource

Proposed Voting Choices

Yay or nay.

Patches and Tests

Coming soon ...

Implementation

N/A

References

Pull Request

The competing proposal:

Alphanumeric Decrement

Rejected Features

Keep this updated with features that were discussed on the mail lists.

rfc/normalize_inc_dec.1392430365.txt.gz · Last modified: 2017/09/22 13:28 (external edit)