- October 2020
- June 2020
- May 2020
- October 2019
- June 2019
- September 2018
- May 2018
- December 2017
- April 2017
- June 2016
- February 2016
- November 2015
- January 2015
- August 2014
- July 2014
- May 2014
- March 2014
- February 2014
- January 2014
- November 2013
- August 2013
- June 2013
- May 2013
- April 2013
- March 2013
- February 2013
- December 2012
- November 2012
- September 2012
- June 2012
- April 2012
- March 2012
- February 2012
- January 2012
- December 2011
- November 2011
- September 2011
- July 2011
- June 2011
- May 2011
- March 2011
- January 2011
- October 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- September 2009
- July 2009
- June 2009
- May 2009
- March 2009
- September 2008
- April 2008
- December 2007
- June 2007
- June 2005
- September 2004
- May 2002
- October 2001
- August 2001
2010-02-15: array_slice is not confused about negative length
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 ($a, 2, -2));
print_r (array_slice ($a, 2, -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