rfc:negative-index-support

Request for Comments: Negative index support

Introduction

The purpose this RFC using negative offsets is to extend the current positive indices support for strings and arrays to allow negative values.

Examples

Without the support of negative indices to find the character 'd' in 'Hello World' can be done in using various ways

$string = 'Hello World';
 
// using substr
$letter_d = substr($string, strlen($string) -1);
 
// using a positive index value
$letter_d = $string[strlen($string) -1];

Using the same example but using a negative index would be

$string = 'Hello World';
 
$letter_d = $string[-1];

The same could be applied to arrays that are not keyed

$array = array(1001, 1002, 1003, 1004);
 
// using a positive index value
$number_1004 = $array[count($array) -1];
 
// or using array_slice
$number_1004 = array_slice($array, -1, 1)[0];

Using a negative index

$array = array(1001, 1002, 1003, 1004);
 
$number_1004 = $array[-1];

What about associated arrays?

No change. As associated arrays can have numerical keys.

Out of bound negative indices

Same notice to be shown as the current out of bound for positive indices that have exceed the length of the string/array.

Patch

Changelog

  • 2012-08-30 - Initial RFC
rfc/negative-index-support.txt · Last modified: 2017/09/22 13:28 (external edit)