array_slice

(PHP 4, PHP 5, PHP 7)

array_slice从数组中取出一段

说明

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )

array_slice() 返回根据 offsetlength 参数所指定的 array 数组中的一段序列。

参数

array

输入的数组。

offset

如果 offset 非负,则序列将从 array 中的此偏移量开始。如果 offset 为负,则序列将从 array 中距离末端这么远的地方开始。

length

如果给出了 length 并且为正,则序列中将具有这么多的单元。如果给出了 length 并且为负,则序列将终止在距离数组末端这么远的地方。如果省略,则序列将从 offset 开始一直到 array 的末端。

preserve_keys

注意 array_slice() 默认会重新排序并重置数组的数字索引。你可以通过将 preserve_keys 设为 TRUE 来改变此行为。

返回值

返回其中一段。 如果 offset 参数大于 array 尺寸,就会返回空的 array。

更新日志

版本 说明
5.2.4 length 参数默认值改成 NULL。 现在 lengthNULL 时,意思是说使用 array 的长度。 之前的版本里, NULLlength 的意思是长度为零(啥也不返回)。
5.0.2 增加了可选参数 preserve_keys

范例

Example #1 array_slice() 例子

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

$output array_slice($input2);      // returns "c", "d", and "e"
$output array_slice($input, -21);  // returns "d"
$output array_slice($input03);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input2, -1));
print_r(array_slice($input2, -1true));
?>

以上例程会输出:

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

参见

User Contributed Notes

SomeGuy 24-Jun-2016 06:17
Thank to taylorbarstow here the function with the unset feature.
<?php
function array_slice_assoc(&$array,$keys,$unset = true) {
   
$return = array_intersect_key($array, array_flip($keys));
    if (
$unset) {
        foreach (
$keys as $value) {
            unset(
$array[$value]);
        }
    }
    return
$return;
}
?>
barakpinch at gmail dot com 22-May-2016 03:37
array_slice($array, $start, $length)

about the array_slices's $length argument:
 a positive decimal number is rounded down (e.g. 1.5 -> 1), a negative decimal is rounded up (e.g. -0.5 -> 0)
kansey 12-Aug-2015 06:32
To save the sort order of a numeric index in the array. Version php =>5.5.26
/*
Example
*/

$arr = array( "1" =>2, "2" =>3 , "3" =>5 );

print_r(array_slice($arr,1,null,true));

/*
Result

Array
(
[2] => 3
[3] => 5
)
*/
richardpq at gmail dot com 02-Aug-2015 06:24
@robert_johnson is incorrect, is not that php 5.5 preserver the keys is that the documentation is very clear:

"...will reorder and reset the numeric array indices" so the key here is NUMERIC array indices, therefor:
<?php
$test
= array(
   
1=>'hello 1',
   
2=>'hello 2',
   
3=>'hello 3',
   
4=>'hello 4',
   
5=>'hello 5',
   
6=>'hello 6',
   
7=>'hello 7',
   
8=>'hello 8'
);
print_r( array_slice($test,2,5) );
?>
Will print:
Array
(
    [0] => hello 3
    [1] => hello 4
    [2] => hello 5
    [3] => hello 6
    [4] => hello 7
)
kezzyhko at gmail dot com 27-Jul-2015 03:49
( If $offset is negative and abs($length)>count($length) ) or ( $offset>count($array) ) etc, array_slice returns empty array. For example:

<?php

$array
= array(
   
'a'=>'1',
   
'b'=>'2',
   
'c'=>'3',
   
'd'=>'4',
   
'e'=>'5',
   
'f'=>'6',
   
'g'=>'7',
   
'h'=>'8'
);

print_r( array_slice($test, 2, -10) );
print_r( array_slice($test, 10, 1) );
print_r( array_slice($test, 10, 15) );

//prints
//Array()
//Array()
//Array()

?>
fraterjan at gmail dot com 18-Oct-2014 07:14
To make sure numerical key values for associative arrays are not converted to integers set $preserve_keys = true.

Example:
$slice = array_slice($array, 0, 3, $preserve_keys = true);
robert dot johnson at icap dot com 12-Sep-2014 06:58
array_slice() seems to work on associative arrays and preserves the keys.  I just ran this test on PHP 5.5:

<?php
$test
= array(
   
'a'=>'hello 1',
   
'r'=>'hello 2',
   
'h'=>'hello 3',
   
'w'=>'hello 4',
   
't'=>'hello 5',
   
'n'=>'hello 6',
   
'k'=>'hello 7',
   
'b'=>'hello 8');
print_r( array_slice($test,2,5) );
?>

Output:
Array
(
    [h] => hello 3
    [w] => hello 4
    [t] => hello 5
    [n] => hello 6
    [k] => hello 7
)
info [at] saiptek.com 12-Mar-2014 10:04
Here is analog to this function. Hope that it helps

function filter_array($input_array, $filter_from, $filter_to)
        {        
            $output_array = array();
           
            foreach ($input_array as $key => $value)
            {
                if($key>=$filter_from && $key<=$filter_to)
                {
                    $output_array[] = $value;
                }
                elseif ($key>$filter_to)
                {
                    //if the key is larger than what we want to filter
                    //it is useless to continue looping
                    break;
                }
                else
                {
                    //if the key is smaller than what we expect
                    continue;
                }
               
            }
           
            return $output_array;
        }

// you can add more security defenses for the variables - e.g. if it is string or something like that
Ray.Paseur often uses Gmail 06-Jun-2013 11:44
<?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;
}
gary at wits dot sg 11-Jun-2011 08:44
I've found this useful.
The following is a function used to shuffle a very specific part of the array, by providing start and end index.

<?php
function array_shuffle_section(&$a, $s, $e) {
   
$head = array_slice($a, 0, $s);
   
$body = array_slice($a, $s, $e-$s+1);
   
$tail = array_slice($a, $e+1);

   
shuffle($body);
   
$a = array_merge($head,$body,$tail);
}
?>
Nathan - thefiscster510 at gmail dot com 29-Mar-2011 07:38
If you want to remove a specified entry from an array i made this mwethod...

<?php
$array
= array("Entry1","entry2","entry3");

$int = 3; //Number of entries in the array
$int2 = 0; //Starter array spot... it will begine its search at 0.
$del_num = 1; //Represents the second entry in the array... which is the one we will happen to remove this time... i.e. 0 = first entry, 1 = second entry, 2 = third...........

$newarray = array(); //Empty array that will be the new array minus the specified entry...
print_r($array) . "<br>";    //print original array contents
print_r($newarray). "<br>"; //print the new empty array

do
{
$user = $array[$int2];
$key = array_search($user, $array);
if (
$key == $del_num)
{

}
else
{
$newarray[] = $array[$int2];
}

$int2 = $int2 + 1;
} while (
$int2 < $int);

print_r($newarray). "<br>"; //print the new array

?>
delew 11-Feb-2011 10:17
just a little tip.
to preserve keys without providing length: use NULL

array_slice($array, $my_offset, NULL, true);
xananax at yelostudio dot com 03-Feb-2011 04:23
<?php
/**
 * Reorders an array by keys according to a list of values.
 * @param array $array the array to reorder. Passed by reference
 * @param array $list the list to reorder by
 * @param boolean $keepRest if set to FALSE, anything not in the $list array will be removed.
 * @param boolean $prepend if set to TRUE, will prepend the remaining values instead of appending them
 * @author xananax AT yelostudio DOT com
 */
function array_reorder(array &$array,array $list,$keepRest=TRUE,$prepend=FALSE,$preserveKeys=TRUE){
   
$temp = array();
    foreach(
$list as $i){
        if(isset(
$array[$i])){
           
$tempValue = array_slice(
               
$array,
               
array_search($i,array_keys($array)),
               
1,
               
$preserveKeys
           
);
           
$temp[$i] = array_shift($tempValue);
            unset(
$array[$i]);
        }
    }
   
$array = $keepRest ?
        (
$prepend?
           
$array+$temp
           
:$temp+$array
       
)
        :
$temp;
}

/** exemple ** /
$a = array(
    'a'    =>    'a',
    'b'    =>    'b',
    'c'    =>    'c',
    'd'    =>    'd',
    'e'    =>    'e'
);
$order = array('c','b','a');

array_reorder($a,$order,TRUE);
echo '<pre>';
print_r($a);
echo '</pre>';
/** exemple end **/
?>
joel dot a dot villarreal at gmail dot com 20-Oct-2010 12:41
An implementation of array_slice that do not resets the cursor.

<?php
function get_from_array($arr, $start, $length)
{
   
$sliced = array();
    foreach (
$arr as $k => $v)
    {
        if (
$start <= $k && $k <= $start + $length - 1)
        {
           
$sliced[] = $v;
            if (
count($sliced) == $length) break; 
        }
    }
    return
$sliced;
}
?>

Cheers,
Joel A. Villarreal Bertoldi
yuwas at ht dot cx 04-Apr-2010 03:54
By combining this with str_split() and implode(),slices can also be excerpted from strings with the following simple function:
<?php
function str_slice($string,$offset,$length=999,$preserve_keys=False){
  if(
$length == 999 ){ $length = strlen($string)-$offset };
 
$slice_arr = array_slice(str_split($string),$offset,$length,$preserve_keys);
  return
implode($slice_arr);
};
?>

Perhaps there's a better way to preset $length.
jamie at jamiechong dot ca 19-Oct-2009 01:04
A flexible array_split function:

<?php
// split the given array into n number of pieces
function array_split($array, $pieces=2)
{  
    if (
$pieces < 2)
        return array(
$array);
   
$newCount = ceil(count($array)/$pieces);
   
$a = array_slice($array, 0, $newCount);
   
$b = array_split(array_slice($array, $newCount), $pieces-1);
    return
array_merge(array($a),$b);
}

// Examples:
$a = array(1,2,3,4,5,6,7,8,9,10);
array_split($a, 2);    // array(array(1,2,3,4,5), array(6,7,8,9,10))
array_split($a, 3);    // array(array(1,2,3,4), array(5,6,7), array(8,9,10))
array_split($a, 4);    // array(array(1,2,3), array(4,5,6), array(7,8), array(9,10))

?>
jamon at clearsightdesign dot com 11-Apr-2009 02:46
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.

<?php

/*
** function array_surround by Jamon Holmgren of ClearSight Design
** Version 1.0 - 4/10/2009
** Please direct comments and questions to my first name at symbol clearsightdesign.com
**
** Returns an array with only the $before and $after number of results
** This is set to work best with MySQL data results
** Use this to find the rows immediately before and after a particular row, as many as you want
**
** Example usage:
**   $mysql_ar is an array of results from a MySQL query and the current id is $cur_id
**   We want to get the row before this one and five rows afterward
**
** $near_rows = array_surround($mysql_ar, "id", $cur_id, 1, 5)
**
**   Previous row is now $near_rows[-1]
**   Current row is now $near_rows[0]
**   Next row is $near_rows[1] ... etc
**   If there is no previous row, $near_rows[-1] will not be set...test for it with is_array($near_rows[-1])
**
*/
function array_surround($src_array, $field, $value, $before = 1, $after = 1) {
    if(
is_array($src_array)) {
       
// reset all the keys to 0 through whatever in case they aren't sequential
       
$new_array = array_values($src_array);
       
// now loop through and find the key in array that matches the criteria in $field and $value
       
foreach($new_array as $k => $s) {
            if(
$s[$field] == $value) {
               
// Found the one we wanted
               
$ck = $k; // put the key in the $ck (current key)
               
break;
            }
        }
        if(isset(
$ck)) { // Found it!
           
$result_start = $ck - $before; // Set the start key
           
$result_length = $before + 1 + $after; // Set the number of keys to return
           
if($result_start < 0) { // Oops, start key is before first result
               
$result_length = $result_length + $result_start; // Reduce the number of keys to return
               
$result_start = 0; // Set the start key to the first result
           
}
           
$result_temp = array_slice($new_array, $result_start, $result_length); // Slice out the results we want
            // Now we have an array, but we want array[-$before] to array[$after] not 0 to whatever.
           
foreach($result_temp as $rk => $rt) { // set all the keys to -$before to +$after
               
$result[$result_start - $ck + $rk] = $rt;
            }
            return
$result;
        } else {
// didn't find it!
           
return false;
        }
    } else {
// They didn't send an array
       
return false;
    }
}

?>

I hope you find this useful! I welcome constructive criticism or comments or of course praise ;) -- just e-mail me.

- Jamon Holmgren
Mr. P 14-Nov-2008 11:11
Note that offset is not the same thing as key. Offset always starts at 0, while keys might be any number.

So this:

<?php print_r(array_slice(array(0 => 0, 5 => 5, 13 => 13),1)); ?>

will result in this:
Array
(
    [0] => 5
    [1] => 13
)
s0i0m at dreamevilconcepts dot com 12-Sep-2008 04:53
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!
ted.devito at 9gmail9 dot 99com 03-May-2008 06:21
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
}
worldclimb at 99gmail99 dot com 21-Mar-2008 09:51
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)
aexchecker at yahoo dot com 04-Oct-2007 05:39
<?php
/**
 * @desc
 * Combines two arrays by inserting one into the other at a given position then
 * returns the result.
 *
 * @since   2007/10/04
 * @version v0.7 2007/10/04 18:47:52
 * @author  AexChecker <AexChecker@yahoo.com>
 * @param   array $source
 * @param   array $destination
 * @param   int [optional] $offset
 * @param   int [optional] $length
 * @return  array
 */
function array_insert($source, $destination, $offset = NULL, $length = NULL) {
    if (!
is_array($source) || empty($source)) {
        if (
is_array($destination) && !empty($destination)) {
            return
$destination;
        }
        return array();
    }
    if (
is_null($offset)) {
        return
array_merge($destination, $source);
    }
   
$offset = var2int($offset);
    if (
is_null($length)) {
        if (
$offset === 0) {
            return
array_merge($source, array_slice($destination, 1));
        }
        if (
$offset === -1) {
            return
array_merge(array_slice($destination, 0, -1), $source);
        }
        return
array_merge(
           
array_slice($destination, 0, $offset),
           
$source,
           
array_slice($destination, ++$offset)
        );
    }
    if (
$offset === 0) {
        return
array_merge($source, array_slice($destination, $length));
    }
   
$destination_count = count($destination);
   
$length = var2int($length);
    if (
$offset > 0) {
        if (
$destination_count - $offset < 1) {
            return
array_merge($destination, $source);
        }
    } else{
        if ((
$t = $destination_count + $offset) < 1) {
            return
array_merge($source, $destination);
        }
       
$offset = $t;
    }
    if (
$length > 0) {
       
$length+= $offset;
    } elseif (
$length < 0 && !($length * -1 < $destination_count)) {
        return
$source;
    } else {
       
$length = $offset;
    }
    return
array_merge(
       
array_slice($destination, 0, $offset),
       
$source,
       
array_slice($destination, $length)
    );
}
?>
phpnotasp at gmail dot com 16-Jul-2007 11:42
It should be noted that this function does NOT modify the original array. So if you need to array_pop() or array_shift() without modifying the original array, you can use array_slice().

<?php

$input
= array('a', 'b', 'c');
$output = array_slice($input, 1);

print_r($output);
print_r($input);

/*
Array
(
    [0] => b
    [1] => c
)
Array
(
    [0] => a
    [1] => b
    [2] => c
)
*/
?>
cpa at NOSPAM dot conceptivator dot com 07-Jun-2007 02:15
'gportlock at gembiz dot co dot uk' has an error in his limitText function. It simply takes a text string, then cuts off the first X words and returns the rest of the string. I believe the intended use is to return only the first X words and cut off the rest.

The correct version should be (notice the inserted 0 offset):
<?php
function limitText( $text, $wordCount )
{
   
$wordArray = explode(" ", $text);
   
array_splice($wordArray, 0, $wordCount);
    return
implode( " ", $wordArray );
}
?>
gportlock at gembiz dot co dot uk 24-May-2007 04:29
This function returns a text string that is limited by the word count. This funtion is particularly useful for paid advertising where you pay by the word.

function limitText( $text, $wordCount ){

        $wordArray = explode(" ", $text);
        array_splice($wordArray, $wordCount);
        return implode( " ", $wordArray );
}
14-Mar-2007 05:09
I noticed that some other people made supportive functions for maintaining numeric keys for PHP versions less than 5.0.2. So here is my version of it.

<?php

//Slice an array but keep numeric keys
function narray_slice($array, $offset, $length) {
   
   
//Check if this version already supports it
   
if (str_replace('.', '', PHP_VERSION) >= 502)
       return
array_slice($array, $offset, $length, true);
       
    foreach (
$array as $key => $value) {
   
        if (
$a >= $offset && $a - $offset <= $length)
           
$output_array[$key] = $value;
       
$a++;
       
    }
   
    return
$output_array;

}

?>
aflavio at gmail dot com 01-Mar-2007 10:43
/**
    * Remove a value from a array
    * @param string $val
    * @param array $arr
    * @return array $array_remval
    */
    function array_remval($val, &$arr)
    {
          $array_remval = $arr;
          for($x=0;$x<count($array_remval);$x++)
          {
              $i=array_search($val,$array_remval);
              if (is_numeric($i)) {
                  $array_temp  = array_slice($array_remval, 0, $i );
                $array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
                $array_remval = array_merge($array_temp, $array_temp2);
              }
          }
          return $array_remval;
    }

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')
19-Dec-2006 06:10
The version check on "ps at b1g dot de" function fails on my copy of PHP.  My Version of PHP is "4.3.10-18", and it ends up checking 4310 <=> 502.
Since we are looking for a version over 4.1.0, we cas use version_compare.
 
<?php
   
// PHP >= 5.0.2 is able to do this itself
   
if(function_exists('version_compare') and version_compare(PHP_VERSION, '5.0.2') >= 0) {
      return
array_slice($array, $offset, $length, true);
    }
?>
ps at b1g dot de 03-Nov-2006 11:44
The following function is the same as array_slice with preserve_keys=true, but it works with PHP versions < 5.0.2.
When PHP >= 5.0.2 is available, the function uses the faster PHP-own array_slice-function with preserve_keys=true, otherwise it uses its own  implementation.

<?php
/**
 * array_slice with preserve_keys for every php version
 *
 * @param array $array Input array
 * @param int $offset Start offset
 * @param int $length Length
 * @return array
 */
function array_slice_preserve_keys($array, $offset, $length = null)
{
   
// PHP >= 5.0.2 is able to do this itself
   
if((int)str_replace('.', '', phpversion()) >= 502)
        return(
array_slice($array, $offset, $length, true));

   
// prepare input variables
   
$result = array();
   
$i = 0;
    if(
$offset < 0)
       
$offset = count($array) + $offset;
    if(
$length > 0)
       
$endOffset = $offset + $length;
    else if(
$length < 0)
       
$endOffset = count($array) + $length;
    else
       
$endOffset = count($array);
   
   
// collect elements
   
foreach($array as $key=>$value)
    {
        if(
$i >= $offset && $i < $endOffset)
           
$result[$key] = $value;
       
$i++;
    }
   
   
// return
   
return($result);
}
?>

Good for backwards compatibility I hope somebody might find this useful.
david at bagnara dot org 19-Oct-2006 05:42
I was trying to pass an argument list through the constructors. I tried various things such as func_get_args(). My conclusion is to pass the args to the constructor as an array. Each constructor can remove the fields it wants and pass the array on.

Using the following prototype, each child class can have any number of parameters added to the beginning of the class constructor and the rest passed onto the parent.

If the default value is desired for an argument, just pass NULL.

This could possibly be better done with array_shift or the like.

<?php

class aChild extends aParent
{
   
// TODO customise this list for this class
   
public
       
$a, $b, $c;

    function
__construct( $args = array() )
    {
       
//set up default values for this class
        // TODO customise this list for this class
       
$default = array( "a-def", "b-def", "c-def" ) ;
       
// now overwrite the default with non NULL args
       
foreach( $args as $key=>$val )
        {
           
// more args than needed?
           
if( !isset( $default[$key] ) )
            {
                break;
            }
           
// this arg not null
           
if( isset( $val ) )
            {
               
$default[$key] = $val ;
            }
        }
       
// set this to the new values
        // TODO customise this list for this class
       
list( $this->a, $this->b, $this->c ) = $default ;
       
// take off the ones we used
       
$args = array_slice( $args, count( $default ) ) ;
       
parent::__construct( $args ) ;
    }
}

$x = new aChild( array( "aChild a", NULL, "aChild c", NULL, "aParent second", "aParent third" ) ) ;
?>
06-May-2006 09: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 11: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 06: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 04: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 09-Jul-2005 12: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 ;-)
...
liz at matrixmailing dot com 06-Jun-2005 11: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 10: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 18-Sep-2004 06: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 06: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 11: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 22-Feb-2004 07: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 13-Nov-2002 01: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 03: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 05: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 06: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;     
}
?>