update page now

array_slice

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

array_sliceExtrahiert einen Ausschnitt eines Arrays

Beschreibung

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

array_slice() liefert die mittels offset und length spezifizierte Sequenz von Elementen des Arrays array.

Parameter-Liste

array

Das Eingabe-Array.

offset

Ist offset nicht negativ, beginnt die Sequenz bei diesem Offset in dem array.

Ist offset negativ, beginnt die Sequenz so viele Elemente vor dem Ende von array.

Hinweis:

Der offset Parameter gibt die Position im Array an, nicht den Schlüssel.

length

Ist length angegeben und positiv, enthält die Sequenz bis zu so viele Elemente.

Ist das Array kürzer als length, dann werden nur die verfügbaren Array-Elemente vorhanden sein.

Ist length angegeben und negativ, endet die Sequenz so viele Elemente vor dem Ende des Arrays.

Wenn nicht angegeben, enthält die Sequenz alle Elemente von offset bis zum Ende von array.

preserve_keys

Hinweis:

array_slice() setzt standardmäßig ganzzahlige Schlüssel des Arrays zurück und vergibt sie neu. Dieses Verhalten kann geändert werden, indem preserve_keys auf true gesetzt wird. Zeichenkettenschlüssel werden immer erhalten, unabhängig von diesem Parameter.

Rückgabewerte

Gibt den Ausschnitt zurück. Ist der gewählte offset größer als die Anzahl an Array-Elementen, wird ein leeres Array zurückgegeben.

Beispiele

Beispiel #1 array_slice()-Beispiele

<?php
$input
= array("a", "b", "c", "d", "e");

$output = array_slice($input, 2); // liefert "c", "d" und "e"
$output = array_slice($input, -2, 1); // liefert "d"
$output = array_slice($input, 0, 3); // liefert "a", "b" und "c"

// beachten Sie die Unterschiede in den Schlüsseln
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #2 array_slice() und ein mit 1 beginnendes Array

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

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

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

Beispiel #3 array_slice() und Array mit gemischten Schlüsseln

<?php
$ar
= array('a'=>'Apfel', 'b'=>'Banane', '42'=>'Pfirsisch', 'd'=>'Orange');
print_r(array_slice($ar, 0, 3));
print_r(array_slice($ar, 0, 3, true));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [a] => Apfel
    [b] => Banane
    [0] => Pfirsisch
)
Array
(
    [a] => Apfel
    [b] => Banane
    [42] => Pfirsisch
)

Siehe auch

  • array_chunk() - Splittet ein Array in Teile auf
  • array_splice() - Entfernt einen Teil eines Arrays und ersetzt ihn durch etwas anderes
  • unset() - unset (löschen) einer angegebenen Variablen

add a note

User Contributed Notes 8 notes

up
51
taylorbarstow at the google mail service
19 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
19
Ray.Paseur often uses Gmail
12 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
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
4
ted.devito at 9gmail9 dot 99com
17 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
11
worldclimb at 99gmail99 dot com
17 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
2
Benjamin Sonntag
2 years ago
The documentation doesn't say it, but if LENGTH is ZERO, then the result is an empty array [].
up
8
developer at i-space dot org
23 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
5
s0i0m at dreamevilconcepts dot com
17 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!
To Top