2010-02-15: array_slice is not confused about negative length

Posted at 2010-02-15 13:32:18 by SHD

I enjoy reading the amusingly named www.phpwtf.org on the rare occasions that they add a new post. A recent post complains about negative lengths when using array_slice (actually confusing it with array_splice at one point). Unfortunately, a technical issue means the site doesn't currently accept comments, so I'll simply make a blog post out of my comment there. The info may still be useful to other PHP programmers.

When using array_slice, a negative length does work, but it works differently to what one may expect. It does not start counting backwards from the start point (which would be intuitive, given a negative value for something called "length", nor does it have any result if the calculated end point ends up before the start point. The docs do actually specify this correctly: "If length is given and is negative then the sequence will stop that many elements from the end of the array." So:

<?php
$a 
= array ('a''b''c''d''e');
print_r (array_slice ($a2, -2));
print_r (array_slice ($a2, -1));
?>

outputs:

Array
(
    [0] => c
)
Array
(
    [0] => c
    [1] => d
)

That basically boils down to the following:

<?php
/*
 * Example function that operates as array_slice does *only*
 * with zero-based numerically indexed arrays and when
 * $offset is positive and $length is negative
 */
function slice ($array$offset$length)
{
    
$result = array ();
    for (
$i $offset$i count ($array) + $length; ++$i)
    {
        
$result [] = $array [$i];
    }
    return 
$result;
}
?>

In the example given on phpwtf.org, array_slice ($array, 0, -10) on an array with 1 element, that results in the for loop looping "for ($i = 0; $i < -9; ++$i)", which does nothing. Hence the empty array being returned.

Comments

No comments, yet...

Post a comment

Note: HTML is not permitted, URLs will be linked automatically. Spam comments will result in a permanent ban.
Type these 4 symbols into the edit field