array_slice

(PHP 4, PHP 5)

array_slice -- Выбрать срез массива

Описание

array array_slice ( array array, int offset [, int length [, bool preserve_keys]] )

array_slice() возвращает последовательность элементов массива array, определённую параметрами offset и length.

Если параметр offset положителен, последовательность начнётся на расстоянии offset от начала array. Если offset отрицателен, последовательность начнётся на расстоянии offset от конца array.

Если в эту функцию передан положительный параметр length, последовательность будет включать length элементов. Если в эту функцию передан отрицательный параметр length, в последовательность войдут все элементы исходного массива, начиная с позиции offset и заканчивая позицией, отстоящей на length элементов от конца array. Если этот параметр будет опущен, в последовательность войдут все элементы исходного массива array, начиная с позиции offset.

Обратите внимание, что array_slice() сбрасывает ключи массива. Начиная с PHP 5.0.2 вы можете переопределить это поведение, установив параметр preserve_keys в TRUE.

Пример 1. Пример использования array_slice()

<?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));
?>

Вышеприведённый пример выведет:

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

См. также array_splice() и unset().



array_slice
06-May-2006 12:21
If you specify the fourth argument (to not reassign the keys), then there appears to be no way to get the function to return all values to the end of the array. Assigning -0 or NULL or just putting two commas in a row won't return any results.
taylorbarstow at the google mail service
07-Apr-2006 02:01
Array slice function that works with associative arrays (keys):

function array_slice_assoc($array,$keys) {
   return array_intersect_key($array,array_flip($keys));
}
andreasblixt (at) msn (dot) com
06-Sep-2005 09:53
<?php
  
// Combines two arrays by inserting one into the other at a given position then returns the result
  
function array_insert($src, $dest, $pos) {
       if (!
is_array($src) || !is_array($dest) || $pos <= 0) return FALSE;
       return
array_merge(array_slice($dest, 0, $pos), $src, array_slice($dest, $pos));
   }
?>
ssb45 at cornell dot edu
28-Jul-2005 07:20
In reply to jenny at jennys dot info:

Here is a much easier way to find the $offset of a $key in an $array:

$offset = array_search($key, array_keys($array));
fanfatal at fanfatal dot pl
08-Jul-2005 03:09
Hmm ... i wrote an usefull function whitch is such like strpos but it works on arrays ;]

<?php
/*
 *    Find position of first occurrence of a array
 *
 *    @param array $haystack
 *    @param array $needle
 *    @return int
 *    @author FanFataL
 */
function array_pos($haystack, $needle) {
  
$size = count($needle);
  
$sizeh = count($haystack);
   if(
$size > $sizeh) return false;

  
$scale = $sizeh - $size + 1;

   for(
$i = 0; $i < $scale; $i++)
       if(
$needle === array_slice($haystack, $i, $size))
           return
$i;

   return
false;
}

// Sample:
$a = array('aa','bb','cc','dd','ee');
$b = array('cc','dd');
$pos = array_pos($a, $b);
?>

Greatings ;-)
...
david dot tulloh at infaze dot com dot au
23-Jun-2005 06:26
Nice one liner to extract a column from a 2D array.
It works by using array_slice on every row, through array_map.

<?php
// set up a small test environment
$test_subject[] = array("a", "b", "c");
$test_subject[] = array("d", "e", "f");

$column=1;

// do the actual work
$result = array_map('array_slice', $test_subject,
  
array_fill(0, count($test_subject), $column),
  
array_fill(0, count($test_subject), 1)
);

// and the end result
result == array ( array("b"), array("e") );
?>
liz at matrixmailing dot com
06-Jun-2005 02:16
For those with PHP < 5.0.2, and have a number as your array key, to avoid having the key reset with array_slice, add a blank character to the beginning or end of the key.
<?

$array
[" ".$key] = $value;

?>
bishop
08-Dec-2004 01:58
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:

<?php

$a
= array ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$b = array_pick($a, array ('d', 'b'));

// now:
// $a = array ('a' => 1, 'c' => '3');
// $b = array ('d' => 4, 'b' => '2');

function &array_pick(&$array, $keys)
{
   if (!
is_array($array)) {
      
trigger_error('First parameter must be an array', E_USER_ERROR);
       return
false;
   }

   if (! (
is_array($keys) || is_scalar($keys))) {
      
trigger_error('Second parameter must be an array of keys or a scalar key', E_USER_ERROR);
       return
false;
   }

   if (
is_array($keys)) {
      
// nothing to do
  
} else if (is_scalar($keys)) {
      
$keys = array ($keys);
   }

  
$resultArray = array ();
   foreach (
$keys as $key) {
       if (
is_scalar($key)) {
           if (
array_key_exists($key, $array)) {
              
$resultArray[$key] = $array[$key];
               unset(
$array[$key]);
           }
       } else {
          
trigger_error('Supplied key is not scalar', E_USER_ERROR);
           return
false;
       }
   }

   return
$resultArray;
}

?>
pies at sputnik dot pl
17-Sep-2004 09:29
My shot at Dams's array_slice_key() implementation:

function array_slice_key($array, $offset, $len=-1){

   if (!is_array($array))
       return FALSE;

   $length = $len >= 0? $len: count($array);
   $keys = array_slice(array_keys($array), $offset, $length);
   foreach($keys as $key) {
       $return[$key] = $array[$key];
   }
 
   return $return;
}
Samuele at norsam dot org
05-Apr-2004 09:44
Note that if $offset+$length>count($array) then resulting array will NOT be filled with empty elements at his end, so it is not sure that it will have exactly $length elements. Example:
<?php
$a
=Array(7,32,11,24,65); // count($a) is 5
$b=array_slice($a,2,4);  // 2+4=6, and 6>count($a)
print_r($b);
?>
will return a 3-elements array:
  Array
  (
     [0] => 11
     [1] => 24
     [2] => 65
  )
23-Feb-2004 02:47
Use unset() to delete a associative array.

Ex:
<?php
                                                                                                                              
$item
['chaise'] = array ('qty' => 1,
                      
'desc' => 'Chaise bercante 10"',
                      
'avail' => 10);
                                                                                                                              
$item['divan'] = array ('qty' => 1,
                      
'desc' => 'Divan brun laitte"',
                      
'avail' => 10);
                                                                                                                              
if (isset(
$item['chaise'])) {
       ++
$item['chaise']['qty'];
       }
                                                                                                                              
unset(
$item['divan']);
                                                                                                                              
foreach (
$item as $s) {
       echo
"<br />Commande " . $s['qty'] . " " . $s['desc'];
}
                                                                                                                              
?>
jenny at jennys dot info
21-Feb-2004 10:12
Here's a function which returns the array offset based on the array key.  This is useful if you'd like to use array_slice to get all keys/values after key "foo".

<?
function array_offset($array, $offset_key) {
 
$offset = 0;
  foreach(
$array as $key=>$val) {
   if(
$key == $offset_key)
     return
$offset;
  
$offset++;
  }
  return -
1;
}

$array = array('foo'=>'foo', 'bar'=>'bar', 'bash'=>'bash', 'quux'=>'quux');
print_r($array);
// Prints the following:
// Array
// (
//    [foo] => foo
//    [bar] => bar
//    [bash] => bash
//    [quux] => quux
// )

$offset = array_offset($array,'bar');
// $offset now contains '1'
$new = array_slice($array,$offset+1);
print_r($new);
// Prints the following:
// Array
// (
//    [bash] => bash
//    [quux] => quux
// )
?>
webmaster_nospam at wavesport dot com
12-Nov-2002 04:48
This function may surprise you if you use arbitrary numeric values for keys, i.e.

<?php
//create an array
$ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange');

print_r($ar);
// print_r describes the array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [42] => pear
//    [d] => orange
// )

//use array_slice() to extract the first three elements
$new_ar = array_slice($ar, 0, 3);

print_r($new_ar);
// print_r describes the new array as:
// Array
// (
//    [a] => apple
//    [b] => banana
//    [0] => pear
// )
?>

The value 'pear' has had its key reassigned from '42' to '0'.

When $ar is initially created the string '42' is automatically type-converted by array() into an integer.  array_slice() and array_splice() reassociate string keys from the passed array to their values in the returned array but numeric keys are reindexed starting with 0.
t dot oddy at ic dot ac dot uk
25-Apr-2002 06:47
[Editor's Note:
It is easier to do the same thing using array_values()
]
array_slice() can be used to "re-index" an array to start from key 0.  For example, unpack creates an array with keys starting from 1;

<?php
var_dump
(unpack("C*","AB"));
?>

produces

<?php
array(2) {
  [
1]=>
 
int(65)
  [
2]=>
 
int(66)
}
?>

and

<?php
var_dump
(array_slice(unpack("C*","AB"),0));
?>

give you

<?php
array(2) {
  [
0]=>
 
int(65)
  [
1]=>
 
int(66)
}
?>
developer at i-space dot org
03-Feb-2002 08:22
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.
richardgere at jippii dot fi
27-Jan-2002 09:14
The same thing, written by a maladroit :)

<?php
function array_slice2( $array, $offset, $length = 0 )
{
  if(
$offset < 0 )
  
$offset = sizeof( $array ) + $offset;

 
$length = ( !$length ? sizeof( $array ) : ( $length < 0 ? sizeof( $array ) - $length : $length + $offset ) );

  for(
$i = $offset; $i < $length; $i++ )
  
$tmp[] = $array[$i];

  return
$tmp;     
}
?>
dams at php dot net
15-Dec-2001 07:09
Here is a version of Array_slice which takes into account keys.

That may be a suggestion for future developpement.

<?php
function array_slice_key($array, $offset){
  if (!
is_array($array))
     return
FALSE;
    
  if (
func_num_args() == 3){
  
$length = func_get_arg(2);
  
$length = max(0,intval($length));
  } else {
  
$length = count($array);
  }
 
 
$i = 0;
 
$return = array();
 
$keys = array_slice(array_keys($array), $offset, $length);
  foreach(
$keys as $key){
  
$return[$key] = $array[$key];
  }
  return
$return;
}
?>

<array_shiftarray_splice>
 Last updated: Tue, 15 Nov 2005