Re: Support negative indexes for arrays and strings

From: Date: Fri, 31 Aug 2012 13:14:10 +0000
Subject: Re: Support negative indexes for arrays and strings
Groups: php.internals 
Request: Send a blank email to internals+get-62606@lists.php.net to get a copy of this message
Having thought about this for a while, I think this is a bad idea - here's why: $array = array(1001, 1002, 1003, 1004); $number = $array[-1]; // => 1004 $number[-1] = 1005; $number = $array[-1]; // => ???? Obviously, the last statement must return 1005, since otherwise that value would be inaccessible. On the other hand, to know whether you have to know whether your array is currently a hash or not - since array index now works completely differently depending on whether your array is currently a hash or an array. This is not something you can currently even test for - and not something you should really need to know or care about in the first place. Having to know this information in certain cases would defeat the purpose of having a single collection-type in the first place: it really *should* work the same, all the time. Just my $0.02... -- From: Marc Easen <marc@easen.co.uk> To: "internals@lists.php.net" <internals@lists.php.net>, Lars Strojny <lars@strojny.net> Cc: Date: Sun, 17 Jun 2012 20:53:38 +0100 Subject: Re: [PHP-DEV] Support negative indexes for arrays and strings 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

« previous php.internals (#62606) next »