Re: Support negative indexes for arrays and strings

From: Date: Sun, 17 Jun 2012 19:53:38 +0000
Subject: Re: Support negative indexes for arrays and strings
References: 1 2 3 4 5 6 7  Groups: php.internals 
Request: Send a blank email to internals+get-60871@lists.php.net to get a copy of this message
Hi Lars, I don't think there needs to be a new operator, as it is possible to achieve this behaviour without adding a new language construct. The odd thing with PHP as I'm sure you are aware of is that arrays can be either a lists or a dictionary. This is where this becomes quite difficult to implement: Numerical keyed array:
    $a = array('foo', 'bar', 'baz');
    $a[0] === 'foo'
I would expect:
    $a[-1] === 'baz';
An string keyed array:
    $b = array('foo' => 1, 'bar' => 2, 'baz' => 3);
    $b[0] === 1;
Would generate an E_NOTICE: PHP Notice: Undefined offset: 0 in php shell code on line 1. An negative offset would also generate the same E_NOTICE. So going back to your point, the change would only be to numeric based arrays (list) and strings. It could be possible to string keyed arrays to be accessed by the numeric counter parts, but I'm not familiar to comment on if this is even possible. It seems this topic has generated a lot of interest, I feel the best way to proceed would be to write a RFC. I've never written one before so could someone give me access to create a page on the RFC site or create a RFC for me and give me permission to update it, my username is 'easen'. Thanks, Marc On 17/06/12 15:14, Lars Strojny wrote:
Hi Marc, Am 11.06.2012 um 23:01 schrieb Marc Easen: [...]
I don't see much of complex logic here, but $a[2] = 'a' would create a new array element if it does not exist, while $a[-2] can't. Not a big issue, but somewhat inconsistent I guess.
Please note I'm not referring the negative indexes in arrays, just strings. As I see strings as being simpler to implement and produce a greater benefit compared to supporting negative indexes for arrays. As arrays are more complex structures and adding this behaviour would complicate things somewhat.
I would propose not to try implementing a different behavior for strings than it is for arrays. I think we need a more convenient way to access parts of a string/parts of an array than substr() and array_slice() provide. But this will most likely be a new operator. cu, Lars


« previous php.internals (#60871) next »