GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Downloads
  • Documentation
  • Get Involved
  • Help
  • Getting Started
  • Introduction
  • A simple tutorial
  • Language Reference
  • Basic syntax
  • Types
  • Variables
  • Constants
  • Expressions
  • Operators

This view

  • Original page
  • New address

GeezerVison is showing www.php.net — PHP: array_slice - Manual

PHP 8.6.0RC7 available for testing
    array_splice »
    « array_shift
    • Preface
    • Function Reference
    • Variable and Type Related Extensions
    • Arrays
    • Array Functions

    array_slice

    (PHP 4, PHP 5, PHP 7, PHP 8)

    array_slice — Extract a slice of the array

    Description

    function array_slice(
        array $array,
        int $offset,
        ?int $length = null,
        bool $preserve_keys = false
    ): array

    array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.

    Parameters

    array

    The input array.

    offset

    If offset is non-negative, the sequence will start at that offset in the array.

    If offset is negative, the sequence will start that far from the end of the array.

    Note:

    The offset parameter denotes the position in the array, not the key.

    length

    If length is given and is positive, then the sequence will have up to that many elements in it.

    If the array is shorter than the length, then only the available array elements will be present.

    If length is given and is negative then the sequence will stop that many elements from the end of the array.

    If it is omitted, then the sequence will have everything from offset up until the end of the array.

    preserve_keys

    Note:

    array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to true. String keys are always preserved, regardless of this parameter.

    Return Values

    Returns the slice. If the offset is larger than the size of the array, an empty array is returned.

    Examples

    Example #1 array_slice() examples

    <?php
    $input = array("a", "b", "c", "d", "e");
    
    $output = array_slice($input, 2);      // returns "c", "d", and "e"
    $output = array_slice($input, -2, 1);  // returns "d"
    $output = array_slice($input, 0, 3);   // returns "a", "b", and "c"
    
    // note the differences in the array keys
    print_r(array_slice($input, 2, -1));
    print_r(array_slice($input, 2, -1, true));
    ?>

    The above example will output:

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

    Example #2 array_slice() and one-based array

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

    The above example will output:

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

    Example #3 array_slice() and array with mixed keys

    <?php
    $ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');
    print_r(array_slice($ar, 0, 3));
    print_r(array_slice($ar, 0, 3, true));
    ?>

    The above example will output:

    Array
    (
        [a] => apple
        [b] => banana
        [0] => pear
    )
    Array
    (
        [a] => apple
        [b] => banana
        [42] => pear
    )

    See Also

    • array_chunk() - Split an array into chunks
    • array_splice() - Remove a portion of the array and replace it with something else
    • unset() - unset a given variable

    Found A Problem?

    Learn How To Improve This Page • Submit a Pull Request • Report a Bug
    +add a note

    User Contributed Notes 8 notes

    up
    down
    51
    taylorbarstow at the google mail service ¶
    20 years ago
    Array slice function that works with associative arrays (keys):
    
    function array_slice_assoc($array,$keys) {
        return array_intersect_key($array,array_flip($keys));
    }
    up
    down
    19
    Ray.Paseur often uses Gmail ¶
    13 years ago
    <?php
    // CHOP $num ELEMENTS OFF THE FRONT OF AN ARRAY
    // RETURN THE CHOP, SHORTENING THE SUBJECT ARRAY
    function array_chop(&$arr, $num)
    {
        $ret = array_slice($arr, 0, $num);
        $arr = array_slice($arr, $num);
        return $ret;
    }
    up
    down
    7
    nathan dot fiscaletti at gmail dot com ¶
    8 years ago
    If you want an associative version of this you can do the following:
    
    function array_slice_assoc($array,$keys) {
        return array_intersect_key($array,array_flip($keys));
    }
    
    However, if you want an inverse associative version of this, just use array_diff_key instead of array_intersect_key. 
    
    function array_slice_assoc_inverse($array,$keys) {
        return array_diff_key($array,array_flip($keys));
    }
    
    Example:
    
    $arr = [
        'name' => 'Nathan',
        'age' => 20,
        'height' => 6
    ];
    
    array_slice_assoc($arr, ['name','age']);
    
    will return 
    
    Array (
         'name' = 'Nathan',
         'age' = 20
    )
    
    Where as
    
    array_slice_assoc_inverse($arr, ['name']);
    
    will return 
    
    Array (
        'age' = 20,
        'height' = 6
    )
    up
    down
    4
    ted.devito at 9gmail9 dot 99com ¶
    18 years ago
    based on worldclimb's arem(), here is a recursive array value removal tool that can work with multidimensional arrays.
    
    function remove_from_array($array,$value){
        $clear = true;
        $holding=array();
       
        foreach($array as $k => $v){
            if (is_array($v)) {
                $holding [$k] = remove_from_array ($v, $value);
                }
            elseif ($value == $v) {
                $clear = false;
                }
            elseif($value != $v){
                $holding[$k]=$v; // removes an item by combing through the array in order and saving the good stuff
            }
        }   
        if ($clear) return $holding; // only pass back the holding array if we didn't find the value 
    }
    up
    down
    12
    worldclimb at 99gmail99 dot com ¶
    18 years ago
    array_slice can be used to remove elements from an array but it's pretty simple to use a custom function.
    
    One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function's names.
    
    <?
    function arem($array,$value){
        $holding=array();
        foreach($array as $k => $v){
            if($value!=$v){
                $holding[$k]=$v;
            }
        }    
        return $holding;
    }
    
    function akrem($array,$key){
        $holding=array();
        foreach($array as $k => $v){
            if($key!=$k){
                $holding[$k]=$v;
            }
        }    
        return $holding;
    }
    
    $lunch = array('sandwich' => 'cheese', 'cookie'=>'oatmeal','drink' => 'tea','fruit' => 'apple');
    echo '<pre>';
    print_r($lunch);
    $lunch=arem($lunch,'apple');
    print_r($lunch);
    $lunch=akrem($lunch,'sandwich');
    print_r($lunch);
    echo '</pre>';
    ?>
    
    (remove 9's in email)
    up
    down
    2
    Benjamin Sonntag ¶
    3 years ago
    The documentation doesn't say it, but if LENGTH is ZERO, then the result is an empty array [].
    up
    down
    8
    developer at i-space dot org ¶
    24 years ago
    remember that array_slice returns an array with the current element. you must use array_slice($array, $index+1) if you want to get the next elements.
    up
    down
    5
    s0i0m at dreamevilconcepts dot com ¶
    18 years ago
    Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It's usage is like so:
    
    $array['admin'] = array('blah1', 'blah2');
    $array['voice'] = array('blah3', 'blah4');
    array_cut('blah4', $array);
    
    ...Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this...
    
    Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) ) 
    
    Here is the code...
    
    <?php
    
      function varname ($var)
      {
        // varname function by dcez at land dot ru
        return (isset($var)) ? array_search($var, $GLOBALS) : false;
      }
    
      function array_cut($needle, $haystack)
      {
        foreach ($haystack as $k => $v)
        {
          for ($i=0; $i<count($v); $i++)
            if ($v[$i] === $needle)
            {
              return array_splice($GLOBALS[varname($haystack)][$k], $i, 1);
              break; break;
            }
        }
    
    ?>
    
    Check out dreamevilconcept's forum for more innovative creations!
    +add a note
    • Array Functions
      • array
      • array_​all
      • array_​any
      • array_​change_​key_​case
      • array_​chunk
      • array_​column
      • array_​combine
      • array_​count_​values
      • array_​diff
      • array_​diff_​assoc
      • array_​diff_​key
      • array_​diff_​uassoc
      • array_​diff_​ukey
      • array_​fill
      • array_​fill_​keys
      • array_​filter
      • array_​find
      • array_​find_​key
      • array_​first
      • array_​flip
      • array_​intersect
      • array_​intersect_​assoc
      • array_​intersect_​key
      • array_​intersect_​uassoc
      • array_​intersect_​ukey
      • array_​is_​list
      • array_​key_​exists
      • array_​key_​first
      • array_​key_​last
      • array_​keys
      • array_​last
      • array_​map
      • array_​merge
      • array_​merge_​recursive
      • array_​multisort
      • array_​pad
      • array_​pop
      • array_​product
      • array_​push
      • array_​rand
      • array_​reduce
      • array_​replace
      • array_​replace_​recursive
      • array_​reverse
      • array_​search
      • array_​shift
      • array_​slice
      • array_​splice
      • array_​sum
      • array_​udiff
      • array_​udiff_​assoc
      • array_​udiff_​uassoc
      • array_​uintersect
      • array_​uintersect_​assoc
      • array_​uintersect_​uassoc
      • array_​unique
      • array_​unshift
      • array_​values
      • array_​walk
      • array_​walk_​recursive
      • arsort
      • asort
      • compact
      • count
      • current
      • end
      • extract
      • in_​array
      • key
      • key_​exists
      • krsort
      • ksort
      • list
      • natcasesort
      • natsort
      • next
      • pos
      • prev
      • range
      • reset
      • rsort
      • shuffle
      • sizeof
      • sort
      • uasort
      • uksort
      • usort
    • Deprecated
      • each
    You are visitor 01402503 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.