[UPHPU] array_slice offset inconsistency?
Jonathan Duncan
jonathan at bluesunhosting.com
Sat Jan 30 21:58:34 MST 2010
On 30 Jan 2010, at 21:45, Wade Preston Shearer wrote:
> On 30 Jan 2010, at 21:38, Jonathan Duncan wrote:
>
>> Maybe it is just late, but this is bugging me.
>>
>> I got this example from the PHP documentation (http://us3.php.net/manual/en/function.array-slice.php):
>>
>> $input = array("a", "b", "c", "d", "e");
>>
>> $output = array_slice($input, 2); // returns "c", "d", and "e"
>> print_r($output);
>> $output = array_slice($input, -2, 1); // returns "d"
>> print_r($output);
>> $output = array_slice($input, 0, 3); // returns "a", "b", and "c"
>> print_r($output);
>>
>> What is baffling me is why the second array_slice returns "d" instead of "c", "d".
>>
>> Perhaps the wording they use in the offset gives away the answer, but if so, then I submit that they are being inconsistent. An array starts counting at 0 (unless you specify otherwise). If the non-negative offset specified is 2 then is will start at the third offset. One would think that the negative offset should work the same way, but in reverse.
>>
>> Someone set me straight, please. I need to just put this down for the night.
>
> Regardless of the type of indexing used from the end, it doesn't make sense for example 2 to return more than one item. The third (optional) value passed into the array is length.
>
Agreed, that would be another inconsistency. Because if the length specified is positive, then it acts as a length, if it is negative, then it is the length from the end not necessary the length of the slice. Argh.
> I agree with you that it is inconsistent of them to use zero-based indexing from the front and one-based indexing from the end.
Good, I am glad it is not just me being crazy. I can rest easy tonight.
Thanks.
More information about the UPHPU
mailing list