Slice a array (like MySQLs limit)

This example shows how you can slice a array to a specific size like you would use the MySQL limit command.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
03/28/2006

Updated:
10/29/2007

Tags:


// Example usage of the build-in array slice method:
 
$ExampleArray = array(1, 2, 3, 4, 5, 6);
 
$ResultArray = array_slice($array, 0, 4);
 
print_r($ResultArray);
 
/*
 
Returns: 
    array(1, 2, 3, 4)
 
*/
 
 
/*
** My old method (deprecated)
**
** I created this method before I found the array_slice method.
*/
function ArrayLimit($InputArray, $From, $Length=0){
 
    $NewArray = array();
    $Length = ($Length==0) ? count($InputArray) - $From : $Length;
    $c = 0;
 
    reset($InputArray);
    while(list($k,$v) = each($InputArray)){
 
        if ($c >= $From && $c < $Length)
            $NewArray[$k] = $v;
        else 
            break; 
 
        $c++;
    }
 
    return $NewArray;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

dave May 19, 2010 at 23:25
Oops... just say the update at the top. Well if anyone else missed it too at first glance, array_slice() is the way to do this.
dave May 19, 2010 at 23:24
There is a built-in function array_slice() that would do this quicker.
Junaid Atari August 01, 2009 at 13:56
Nice function. I like it!