RE: [PHP-DEV] Support negative indexes for arrays and strings
Hi, Instead of [], which is ambiguous, couldn't we just extend the {} syntax : we already have $a{offset} working with positive numbers, couldn't we extend it to accept negative offsets also ? François -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On 03.09.2012, at 01:11, sle...@pipeline.com wrote: I see how this may work for strings and simple vectors, but what about this: $a = array(-1 = foo, -2 = bar); echo $a[-1]; It should keep returning foo, right? So then the question is - what $array[-1] actually means? Context would be the deciding factor, i.e. perhaps restrict the shortcut's applicability to only a positive sequence of numbers for an indexed array's keys, as follows: $a = array(10 = pen, 11 = heaven); echo $a[-1]; // heaven You clearly haven't thought this through. What if my code wants to check for the existance of an array index -1, and it doesn't know what kind of array gets passed in? For an index -1, a value would exist, and for a sequential array, it would exist as well. This is an insane can of worms. smime.p7s Description: S/MIME cryptographic signature
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Fri, Aug 31, 2012 at 10:24 PM, Sherif Ramadan theanomaly...@gmail.comwrote: That might actually be something I could use :) But the fun for me begins here: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; What would have happened to the keys? Normally [] is equivalent to [count($numbers)]. This is incorrect, $numbers[] = 6; is not equivalent to $numbers[count($numbers)] = 6; at all, because PHP uses an internal value for this that is represented an unsigned long in the Hashtable ht struct. As it stands today, that code would result in the following: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; var_dump($numbers); /* array(2) { [-1]= int(5) [0]= int(6) } */ Which looks awkward, I know, but the reason is that the internal value that represents the next key to be used when no key is supplied during an array push is an unsigned figure while integer values in PHP are all signed. Since one's complement is used this means the unsigned value will always wrap-around causing -1 to take us back to zero (you can't overflow an unsigned long). Here's how we can see this quirk rearing it's ugly head: $numbers = array(); $numbers[PHP_INT_MAX] = 'foo'; $numbers[] = 'bar'; var_dump($numbers); /* Warning: Cannot add element to the array as the next element is already occupied in ... on line 1 array(1) { [9223372036854775807]= string(3) foo } */ As you can see PHP has a bit of a hickup here. The implementation is such that the index is always initialized to 0 by default and clamped by the API (so when a negative value is supplied we still start back at 0). Here's the actual implementation of array_psuh: for (i = 0; i argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, Cannot add element to the array as the next element is already occupied); efree(args); RETURN_FALSE; } } $array = array(); $array[PHP_INT_MAX+1] = 'foo'; $array[] = 'bar'; var_dump($array); /* array(2) { [-9223372036854775808]= string(3) foo [0]= string(3) bar } */ Another gotchya, of the API is that the representation of the key used in the array and the next available key can be somewhat two misleading. --- On a final note the confusion behind proposing the use of negative indexes for array lookup in PHP is that PHP doesn't really have an array. Something I believe has been discussed at length in the past. Which is why it makes sense to separate the key used in the array from the offset of the element in the ordered map. $array = array(-1 = foo,0 = bar,3 = baz) array_slice($array, -1); // makes perfect sense to me that this would return baz $array = array(-1 = foo,0 = bar,3 = baz) echo $array[-1]; // makes perfect sense to me that this would return foo -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php This discussion kinda reminds me of some of the debates over AUTO_INCREMENT behavior in the MySQL community. Specifically, they end up having to tackle the same funcamental, conceptual dilemma: If I assign/insert/whatever an arbitrary value to a container that can be incremented, and then I direct said container to generate the next increment, what value should that be? What's the most sensible (or perhaps the least unsensible) way to determine that? Of course, I don't really know what the answer is. From a strictly logical standpoint (ignoring the fact that it just doesn't work this way in PHP), my thinking would be that the count-based index approach makes the most sense. I think many (if not most) PHP developers incorrectly assume this to already be the case now. What's my point? I'm not sure that I have one-- but if I did, the point would be that any approach to handling this will likely be problematic in some way or another. That said, I think we should find a way to support negative indexes. There were times when being able to do that would have been very convenient for me. =) --Kris
Re: [PHP-DEV] Support negative indexes for arrays and strings
Sherif Ramadan wrote: As it stands today, that code would result in the following: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; var_dump($numbers); /* array(2) { [-1]= int(5) [0]= int(6) } */ I think that it is just clarifying this further by adding $numbers = array(0,1,2,3,4); Which gives array(7) { [0]= int(0) [1]= int(1) [2]= int(2) [3]= int(3) [4]= int(4) [-1]= int(5) [5]= int(6) } and foreach( $numbers as $value ) { print($value); } gives 0123456 as I would have expected! AND print( $numbers[-1] ); still returns '5' I can NOW use ksort() to really move the '5' to the top of the list. array(7) { [-1]= int(5) [0]= int(0) [1]= int(1) [2]= int(2) [3]= int(3) [4]= int(4) [5]= int(6) } Bottom line ... perhaps we need a DIFFERENT means of identifying position in the array since using -ve keys IS a valid situation in real life. Personally I use -ve positions in the database tables to save having to process all records when adding items at the top, so the associative array quite correctly has -ve key values. I would not want PHP screwing around with that when reading the array in :) I think I am right in saying that 'real array' always start at 0 or 1, and positioning is explicit. So for simple stings then ne6ative indexes make perfect sense. But for PHP 'container arrays' we can legally have -ve keys, and removing that is simply not acceptable. -- Lester Caine - G8HFL - Contact - http://lsces.co.uk/wiki/?page=contact L.S.Caine Electronic Services - http://lsces.co.uk EnquirySolve - http://enquirysolve.com/ Model Engineers Digital Workshop - http://medw.co.uk Rainbow Digital Media - http://rainbowdigitalmedia.co.uk -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
This discussion kinda reminds me of some of the debates over AUTO_INCREMENT behavior in the MySQL community. Specifically, they end up having to tackle the same funcamental, conceptual dilemma: If I assign/insert/whatever an arbitrary value to a container that can be incremented, and then I direct said container to generate the next increment, what value should that be? What's the most sensible (or perhaps the least unsensible) way to determine that? Of course, I don't really know what the answer is. From a strictly logical standpoint (ignoring the fact that it just doesn't work this way in PHP), my thinking would be that the count-based index approach makes the most sense. I think many (if not most) PHP developers incorrectly assume this to already be the case now. What's my point? I'm not sure that I have one-- but if I did, the point would be that any approach to handling this will likely be problematic in some way or another. That said, I think we should find a way to support negative indexes. There were times when being able to do that would have been very convenient for me. =) --Kris I really think people are misunderstanding both the problem and the solution here so I will try to make this very simple. * Problem: Finding an element in a PHP array by its offset * Solution: array_slice($array, -1) * Confusion: Array offsets are not indexes or array keys * Deep confusion: $array[-1] can be used to access an element by its offset * Twilight Zone: PHP Arrays are ordered by their keys The problem here is not that PHP doesn't support or allow you to access the element in an array by its offset or that a negative offset can't reach into the bottom/end of the array. The problem is that people are confusing an offset with an index. PHP arrays have keys. The $array[key] syntax allows us to access an array element by its key, not by its offset. The reason is simple: PHP Arrays are ordered hashmaps (they are made up of ordered key/value pairs). To confuse people now by modifying this syntax to allow you to do what array_slice() already does perfectly well, would make using the same syntax for accessing array values by their keys impossible. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Sat, Sep 1, 2012 at 4:52 AM, Lester Caine les...@lsces.co.uk wrote: Sherif Ramadan wrote: As it stands today, that code would result in the following: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; var_dump($numbers); /* array(2) { [-1]= int(5) [0]= int(6) } */ I think that it is just clarifying this further by adding $numbers = array(0,1,2,3,4); Which gives array(7) { [0]= int(0) [1]= int(1) [2]= int(2) [3]= int(3) [4]= int(4) [-1]= int(5) [5]= int(6) } I have no idea how it would. I think you supplied the wrong code here. and foreach( $numbers as $value ) { print($value); } gives 0123456 as I would have expected! AND print( $numbers[-1] ); still returns '5' I can NOW use ksort() to really move the '5' to the top of the list. array(7) { [-1]= int(5) [0]= int(0) [1]= int(1) [2]= int(2) [3]= int(3) [4]= int(4) [5]= int(6) } Bottom line ... perhaps we need a DIFFERENT means of identifying position in the array since using -ve keys IS a valid situation in real life. Personally I use -ve positions in the database tables to save having to process all records when adding items at the top, so the associative array quite correctly has -ve key values. I would not want PHP screwing around with that when reading the array in :) I can't understand what you mean by Different means of identifying position in the array? If you mean a way to access an array's element by its position in the array then yes, we already have that. It's called array_slice() see http://php.net/array-slice which allows you to access elements in the array by their offset and that includes using a negative offset. The key and the offset are two completely different things. I think I am right in saying that 'real array' always start at 0 or 1, and positioning is explicit. So for simple stings then ne6ative indexes make perfect sense. But for PHP 'container arrays' we can legally have -ve keys, and removing that is simply not acceptable. Yes, the position is always explicit, the key isn't ever responsible for determining the position of an element in the array. The value of the PHP key has never been responsible for determining the position of the element in the array. $array[9] = 'first element'; $array[0] = 'second element'; var_dump($array); /* array(2) { [9]= string(13) first element [0]= string(14) second element } */ $array[0] = 'first element'; $array[9] = 'second element'; var_dump($array); /* array(2) { [9]= string(14) second element [0]= string(13) first element } */ The order has always been determined internally so the values of these keys mean nothing in terms of order as you can see. -- Lester Caine - G8HFL - Contact - http://lsces.co.uk/wiki/?page=contact L.S.Caine Electronic Services - http://lsces.co.uk EnquirySolve - http://enquirysolve.com/ Model Engineers Digital Workshop - http://medw.co.uk Rainbow Digital Media - http://rainbowdigitalmedia.co.uk -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
$array[0] = 'first element'; $array[9] = 'second element'; var_dump($array); /* array(2) { [9]= string(14) second element [0]= string(13) first element } */ Just correcting this as it was a copy/paste fail... The above code would produce: array(2) { [0]= string(13) first element [9]= string(14) second element } -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Sherif Ramadan wrote: I can't understand what you mean by Different means of identifying position in the array? If you mean a way to access an array's element by its position in the array then yes, we already have that. It's called array_slice() seehttp://php.net/array-slice which allows you to access elements in the array by their offset and that includes using a negative offset. The key and the offset are two completely different things. Never had to use it ;) But then there is a heck of a lot of stuff I've never even looked at. But it does blow this thread - when referring to collection arrays - out of the water? The problem I see is people trying to apply 'string' rules in the wrong way ... and I find that string handling works fine for me as it currently works but we probably just need to STOP people trying to apply the same rules to something that is totally different? And I though that 'string' -ve indexes had been sorted? -- Lester Caine - G8HFL - Contact - http://lsces.co.uk/wiki/?page=contact L.S.Caine Electronic Services - http://lsces.co.uk EnquirySolve - http://enquirysolve.com/ Model Engineers Digital Workshop - http://medw.co.uk Rainbow Digital Media - http://rainbowdigitalmedia.co.uk -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Lester Caine wrote: Sherif Ramadan wrote: I can't understand what you mean by Different means of identifying position in the array? If you mean a way to access an array's element by its position in the array then yes, we already have that. It's called array_slice() seehttp://php.net/array-slice which allows you to access elements in the array by their offset and that includes using a negative offset. The key and the offset are two completely different things. Never had to use it ;) But then there is a heck of a lot of stuff I've never even looked at. But it does blow this thread - when referring to collection arrays - out of the water? The problem I see is people trying to apply 'string' rules in the wrong way ... and I find that string handling works fine for me as it currently works but we probably just need to STOP people trying to apply the same rules to something that is totally different? And I though that 'string' -ve indexes had been sorted? OK ... got back form the weekly chore of shopping, and was thinking about what I had said :) Different means of identifying position in the array? I was probably thinking more along the lines of $numbers[-1] is a perfectly valid key on that array, so there is no way that it can be redefined otherwise. It would have to be something completely different such as $numbers[(-1)] to differentiate from the normal use of a key in the array ... and I would have to object strongly to adding that since it is different to other methods. The problem here was accepting that [-1] works differently on a string, and now we are seeing the consequences? It is only valid on a string and so this discussion needs a big brick wall between strings and 'collection arrays' ? People who think they need a position based indexing obviously need educating in the use of the array_slice and the other functions that seem to go with that, but I can see that this method of handling array indexes ( rather than keys ) COULD benefit from a tidy up. As has been discussed in general on the whole array API? -- Lester Caine - G8HFL - Contact - http://lsces.co.uk/wiki/?page=contact L.S.Caine Electronic Services - http://lsces.co.uk EnquirySolve - http://enquirysolve.com/ Model Engineers Digital Workshop - http://medw.co.uk Rainbow Digital Media - http://rainbowdigitalmedia.co.uk -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: Re: [PHP-DEV] Support negative indexes for arrays and strings
On 2012-09-01 21:23, Sherif Ramadan wrote: $array[0] = 'first element'; $array[9] = 'second element'; var_dump($array); /* array(2) { [9]= string(14) second element [0]= string(13) first element } */ Just correcting this as it was a copy/paste fail... The above code would produce: array(2) { [0]= string(13) first element [9]= string(14) second element } Or: ?php $array = []; $array[1] = 42; $array[0] = 17; $array[2] = 99; print_r($array); ? And, just to be explicit, following that up with: ?php reset($array); echo key($array),\t,current($array),\n; next($array); echo key($array),\t,current($array),\n; next($array); echo key($array),\t,current($array),\n; ? === Array ( [1] = 42 [0] = 17 [2] = 99 ) 1 42 0 17 2 99 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: Re: [PHP-DEV] Support negative indexes for arrays and strings
On 2012-09-01 20:17, Kris Craig wrote: This discussion kinda reminds me of some of the debates over AUTO_INCREMENT behavior in the MySQL community. Specifically, they end up having to tackle the same funcamental, conceptual dilemma: If I assign/insert/whatever an arbitrary value to a container that can be incremented, and then I direct said container to generate the next increment, what value should that be? What's the most sensible (or perhaps the least unsensible) way to determine that? Well, in that case SQL provides sequences; iterators that are independent of the column that you might be using them for. You can specify an explicit value or default to the next value from the sequence. If you have a UNIQUE constraint on the column in question a collision would be an error (but since the attempt would have caused the sequence to advance, you could just try again); if not then you end up with two records with the same value in that column. So, in PHP terms, pretty much what there is now - a distinct sequence generator for the array - with the difference being that in the case of key collision the later value overwrites the former. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
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 m...@easen.co.uk To: internals@lists.php.net internals@lists.php.net, Lars Strojny l...@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 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Yes, typo! sorry. $array = array(1001, 1002, 1003, 1004); $number = $array[-1]; // = 1004 $array[-1] = 1005; $number = $array[-1]; // = Looking at the resulting code, I would like to point out also that it's extremely misleading... because $array[-1] references two completely different elements depending on whether you're reading or writing the value... unless $array[-1] = 1005 would actually overwrite the last element in the array - in which case it gets even more dangerous, as well as breaking backwards compatibility... On Fri, Aug 31, 2012 at 9:24 AM, Ferenc Kovacs tyr...@gmail.com wrote: On Fri, Aug 31, 2012 at 3:14 PM, Rasmus Schultz ras...@mindplay.dk wrote: 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. maybe you wanted to write $array[-1] = 1005; instead of $number[-1] = 1005; ? otherwise I can't see the problem that you are mentioning. could you clarify? -- Ferenc Kovács @Tyr43l - http://tyrael.hu -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On 1 Sep, 2012, at 1:11 AM, Rasmus Schultz ras...@mindplay.dk wrote: Yes, typo! sorry. $array = array(1001, 1002, 1003, 1004); $number = $array[-1]; // = 1004 $array[-1] = 1005; $number = $array[-1]; // = Looking at the resulting code, I would like to point out also that it's extremely misleading... because $array[-1] references two completely different elements depending on whether you're reading or writing the value... unless $array[-1] = 1005 would actually overwrite the last element in the array - in which case it gets even more dangerous, as well as breaking backwards compatibility... That might actually be something I could use :) But the fun for me begins here: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; What would have happened to the keys? Normally [] is equivalent to [count($numbers)]. Perhaps this is why JS treats negative indices as properties instead :) On Fri, Aug 31, 2012 at 9:24 AM, Ferenc Kovacs tyr...@gmail.com wrote: On Fri, Aug 31, 2012 at 3:14 PM, Rasmus Schultz ras...@mindplay.dk wrote: 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. maybe you wanted to write $array[-1] = 1005; instead of $number[-1] = 1005; ? otherwise I can't see the problem that you are mentioning. could you clarify? -- Ferenc Kovács @Tyr43l - http://tyrael.hu -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
That might actually be something I could use :) But the fun for me begins here: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; What would have happened to the keys? Normally [] is equivalent to [count($numbers)]. This is incorrect, $numbers[] = 6; is not equivalent to $numbers[count($numbers)] = 6; at all, because PHP uses an internal value for this that is represented an unsigned long in the Hashtable ht struct. As it stands today, that code would result in the following: $numbers = array(); $numbers[-1] = 5; $numbers[] = 6; var_dump($numbers); /* array(2) { [-1]= int(5) [0]= int(6) } */ Which looks awkward, I know, but the reason is that the internal value that represents the next key to be used when no key is supplied during an array push is an unsigned figure while integer values in PHP are all signed. Since one's complement is used this means the unsigned value will always wrap-around causing -1 to take us back to zero (you can't overflow an unsigned long). Here's how we can see this quirk rearing it's ugly head: $numbers = array(); $numbers[PHP_INT_MAX] = 'foo'; $numbers[] = 'bar'; var_dump($numbers); /* Warning: Cannot add element to the array as the next element is already occupied in ... on line 1 array(1) { [9223372036854775807]= string(3) foo } */ As you can see PHP has a bit of a hickup here. The implementation is such that the index is always initialized to 0 by default and clamped by the API (so when a negative value is supplied we still start back at 0). Here's the actual implementation of array_psuh: for (i = 0; i argc; i++) { new_var = *args[i]; Z_ADDREF_P(new_var); if (zend_hash_next_index_insert(Z_ARRVAL_P(stack), new_var, sizeof(zval *), NULL) == FAILURE) { Z_DELREF_P(new_var); php_error_docref(NULL TSRMLS_CC, E_WARNING, Cannot add element to the array as the next element is already occupied); efree(args); RETURN_FALSE; } } $array = array(); $array[PHP_INT_MAX+1] = 'foo'; $array[] = 'bar'; var_dump($array); /* array(2) { [-9223372036854775808]= string(3) foo [0]= string(3) bar } */ Another gotchya, of the API is that the representation of the key used in the array and the next available key can be somewhat two misleading. --- On a final note the confusion behind proposing the use of negative indexes for array lookup in PHP is that PHP doesn't really have an array. Something I believe has been discussed at length in the past. Which is why it makes sense to separate the key used in the array from the offset of the element in the ordered map. $array = array(-1 = foo,0 = bar,3 = baz) array_slice($array, -1); // makes perfect sense to me that this would return baz $array = array(-1 = foo,0 = bar,3 = baz) echo $array[-1]; // makes perfect sense to me that this would return foo -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
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 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 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Hi Marc, Am 17.06.2012 um 21:53 schrieb Marc Easen: [...] 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. I see, must have overread that. This makes it slightly better but not optimal, as too varying behavior for hashes vs. lists will be harder to explain. We could go down that road and separate the both more and more but given the history (and the usage patterns) of arrays in PHP I'm not convinced this is a good idea. I would prefer something like this (and no, I don't propose using ':' as an operator for real): $string = bar; $string:-1 // b $string:-2 // r $string:-10 // NULL $list = array(one, two, three); $list:-1 // three $list:-2 // two $list:-10// NULL $hash = array(one = 1, two = 2, three = 3) $hash:-1 // 3 $hash:-2 // 2 $hash:-10// 10 As using arrays as hashes let’s them behave in a FIFO kind of way, we can do proper slicing. 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'. For sure, RFC makes sense. I like the general idea, I’m just not sure about the syntax. cu, Lars signature.asc Description: Message signed with OpenPGP using GPGMail
[PHP-DEV] Support negative indexes for arrays and strings
I feel that for PHP to incorporate some of the convenience that Python offers is a good particularly with respect to attracting the upcoming generation. PHP needs an injection of new coolness to attract and captivate the imagination of young college-age people who are being exposed to Python as part of their CS curriculum. I think Easen's proposal for PHP to have negative indexing for strings (not arrays) is well-thought out, and conservative too. I think it would be an excellent addition. +1! Sincerely, Sharon -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Mon, June 4, 2012 2:08 pm, Marc Easen wrote: I have submitted a patch to support negative indexs in strings, as per the conversation adding them to arrays could possibly detract from the syntactical sugar they are indented to be. In summary: An alternative to: $var = 'abc'; echo $var[strlen($var) - 1]; Can be: $var = 'abc'; echo $var[-1]; This seems simple enough for a hard-coded -1, but... Would $var[-2] be strlen($var) - 2 and so on? And then one would expect some rather complex logic to compute -N for $var[-N] At that point, this becomes a pretty big WTF, imho. I've never honestly felt it to be a big burden to use strlen($var) - 1, so I don't really see the point, at least for me. -- brain cancer update: http://richardlynch.blogspot.com/search/label/brain%20tumor Donate: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclickhosted_button_id=FS9NLTNEEKWBE -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Hi! Can be: $var = 'abc'; echo $var[-1]; This seems simple enough for a hard-coded -1, but... Would $var[-2] be strlen($var) - 2 and so on? The main question is what happens with foo[-4] or ['x'][-2]. And then one would expect some rather complex logic to compute -N for $var[-N] 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. -- Stanislav Malyshev, Software Architect SugarCRM: http://www.sugarcrm.com/ (408)454-6900 ext. 227 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Mon, June 11, 2012 2:13 pm, Stas Malyshev wrote: And then one would expect some rather complex logic to compute -N for $var[-N] 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. $n = some_incredibly_long_and_complex_computation(); //and, for real fun, sometimes it returns positive, and sometimes negative. $s = $var[$n]; //a few hundred lines later, buried somewhere else if ($n 0){ //whatever } else{ //something entirely different } Sooner or later, somebody will do that, and I really don't want to have to un-tangle all that mess to figure out if $n is positive or negative for the sake of saving a few keystrokes... -- brain cancer update: http://richardlynch.blogspot.com/search/label/brain%20tumor Donate: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclickhosted_button_id=FS9NLTNEEKWBE -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Mon, Jun 11, 2012 at 12:13 PM, Stas Malyshev smalys...@sugarcrm.comwrote: Hi! Can be: $var = 'abc'; echo $var[-1]; This seems simple enough for a hard-coded -1, but... Would $var[-2] be strlen($var) - 2 and so on? The main question is what happens with foo[-4] or ['x'][-2]. The same thing that currently happens for: $f='foo'; echo $f[strlen($f)-4]; $a=['x']; $a[count($a)-2]; which appears to be notices: Notice: Uninitialized string offset: -1 in - on line 2 Notice: Undefined offset: -1 in - on line 3 And then one would expect some rather complex logic to compute -N for $var[-N] 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. Negative indices are currently valid for arrays. If anyone makes use of negative indices, this could break their script. Personally, I'd rather have Marc Easen's behavior.
Re: [PHP-DEV] Support negative indexes for arrays and strings
On 11/06/12 20:28, Richard Lynch wrote: On Mon, June 11, 2012 2:13 pm, Stas Malyshev wrote: And then one would expect some rather complex logic to compute -N for $var[-N] 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. $n = some_incredibly_long_and_complex_computation(); //and, for real fun, sometimes it returns positive, and sometimes negative. $s = $var[$n]; If $n is a negative value, an E_NOTICE will be triggered. To not do if ($n 0){ //whatever } else{ //something entirely different } Prior to your string offset can be looked at being bad practice. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On 11/06/12 20:13, Stas Malyshev wrote: Hi! Can be: $var = 'abc'; echo $var[-1]; This seems simple enough for a hard-coded -1, but... Would $var[-2] be strlen($var) - 2 and so on? The main question is what happens with foo[-4] or ['x'][-2]. And then one would expect some rather complex logic to compute -N for $var[-N] 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. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
I have submitted a patch to support negative indexs in strings, as per the conversation adding them to arrays could possibly detract from the syntactical sugar they are indented to be. In summary: An alternative to: $var = 'abc'; echo $var[strlen($var) - 1]; Can be: $var = 'abc'; echo $var[-1]; Commit: https://github.com/Easen/php-src/commit/7016e52677f525139491467f3e76862b9a597b76 Pull request: https://github.com/php/php-src/pull/100 Thanks, On 14/01/11 18:47, Stas Malyshev wrote: Hi! I would like to open the discussion around the support of negative indexes, as I feel a lot of developers will benefit from this syntactical sugar. What you are looking for is implemented in array_slice(). Python has shortcuts for this thing, like a[1:-1], but PHP doesn't. If you wanted to RFC something here, I think the idea of $a[X:Y] with array_slice semantics could be doable. $a[-1:1] would be your case then.
[PHP-DEV] Support negative indexes for arrays and strings
Hello everyone, I would like to open the discussion around the support of negative indexes, as I feel a lot of developers will benefit from this syntactical sugar. Example: $foo = array(1,2,3); echo $foo[2]; // 3 echo $foo[-1]; // 3 $bar = 'baz'; echo $foo[2]; // 'z' echo $foo[-1]; // 'z' The change to PHP is quite trivial, but as it's a change to language it needs to be discussed. I'm happy to open a RFC, I have got a wiki account but I haven't got permission to add a wiki page. Whom do I need to contact regarding getting correct permissions to add/edit wiki pages? Kind Regards Marc -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
On Fri, Jan 14, 2011 at 10:21 AM, Marc Easen m...@easen.co.uk wrote: Hello everyone, I would like to open the discussion around the support of negative indexes, as I feel a lot of developers will benefit from this syntactical sugar. It would be convenient, but PHP already allows arrays to have negative indices. Changing their behavior would be a major BC break. Best Regards, --Matthew -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Hello everyone, I would like to open the discussion around the support of negative indexes, as I feel a lot of developers will benefit from this syntactical sugar. Example: echo $foo[2]; // 3 echo $foo[-1]; // 3 Negative indexes are used already - for negative indexes. What should: $foo = array(1,2,3, -1 = 4, 5, 6); echo $foo[-1]; return? Now it returns 4. $bar = 'baz'; echo $foo[2]; // 'z' echo $foo[-1]; // 'z' The change to PHP is quite trivial, but as it's a change to language it needs to be discussed. I'm happy to open a RFC, I have got a wiki account but I haven't got permission to add a wiki page. Whom do I need to contact regarding getting correct permissions to add/edit wiki pages? -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php
Re: [PHP-DEV] Support negative indexes for arrays and strings
Hi! I would like to open the discussion around the support of negative indexes, as I feel a lot of developers will benefit from this syntactical sugar. What you are looking for is implemented in array_slice(). Python has shortcuts for this thing, like a[1:-1], but PHP doesn't. If you wanted to RFC something here, I think the idea of $a[X:Y] with array_slice semantics could be doable. $a[-1:1] would be your case then. -- Stanislav Malyshev, Software Architect SugarCRM: http://www.sugarcrm.com/ (408)454-6900 ext. 227 -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php