it will split array into 2 halfs :
<?
function array_split($array)
{
$end=count($array);
$half = ($end % 2 )? ceil($end/2): $end/2;
return array(array_slice($array,0,$half),array_slice($array,$half));
}
//testing with odd count
$array=array('a','b','c','d');
echo "Odd: <br>";
var_dump(array_split($array));
//testing with even count
$array=array('a','b','c','d','f');
echo "Even: <br>";
var_dump(array_split($array));
?>
Output:
===========
Odd:
array(2) {
[0]=>
array(2) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
}
[1]=>
array(2) {
[0]=>
string(1) "c"
[1]=>
string(1) "d"
}
}
Even:
array(2) {
[0]=>
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
[1]=>
array(2) {
[0]=>
string(1) "d"
[1]=>
string(1) "f"
}
}
array_slice
(PHP 4, PHP 5)
array_slice — Extract a slice of the array
Description
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 .
- length
-
If length is given and is positive, then the sequence will have that many elements in it. 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 that array_slice() will reorder and reset the array indices by default. You can change this behaviour by setting preserve_keys to TRUE.
Return Values
Returns the slice.
ChangeLog
| Version | Description |
|---|---|
| 5.0.2 | The optional preserve_keys parameter was added. |
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 )
array_slice
25-Jun-2008 10:02
03-May-2008 07: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
}
21-Mar-2008 10: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)
29-Oct-2007 08:06
Re: 'cpa at NOSPAM dot conceptivator dot com' and 'gportlock at gembiz dot co dot uk'
limitText can be further simplified by adding a limit parameter to the explode function - eliminating the need for the use of array_slice entirely. Note that this only works for extracting the first n words of the string, and not the last.
Also, you've mistakenly used array_splice instead of array_slice in your functions.
<?php
function limitText( $text, $wordCount )
{
$wordArray = explode(" ", $text, $wordCount);
return implode( " ", $wordArray );
}
?>
04-Oct-2007 06: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)
);
}
?>
17-Jul-2007 12: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
)
*/
?>
19-Jun-2007 10:54
People... let's keep things simple here. :) Some of the functions to mimic >5.0.2 behavior (preserving keys) are ridiculously complicated. Look how simple it can be:
<?php
function atrim( $a, $num ) {
while( sizeof( $a ) > $num ) array_pop( $a );
return $a;
}
?>
07-Jun-2007 03: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 );
}
?>
24-May-2007 05: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 );
}
15-Mar-2007 01:41
first at all, ur php version check does not work correctly.
version 4.3.10 (4310 > 520)
Second, $a is not initialized.
Third, to let the function work the same as slice (offset) it should be:
function narray_slice($array, $offset, $length){
$a = 0;
foreach ($array as $key => $value) {
if (($a >= $offset) && ($a - $offset < $length))
$output_array[$key] = $value;
$a++;
}
return $output_array;
}
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;
}
?>
01-Mar-2007 11: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')
16-Feb-2007 02:34
A simple test of this function:
<?php
print_r(array_slice(array('a','b','c','d'), 0, 3)); // normal behaviour
print_r(array_slice(array('a','b','c','d'), 0, 10)); // result: no error, returns as many as possible
print_r(array_slice(array(), 0, 10)); // result: no error, returns empty array
?>
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);
}
?>
05-Nov-2006 01:49
This function can also be used for pure laziness,
<?php
$myVar = end(array_slice(anotherFunction(), 0, 1));
?>
Imagine that anotherFunction() returns, say, three indexes, and you are sure you only want the Nth index, you could use this as a poor man's way of getting by the fact that PHP can't do this:
<?php
$myVar = (anotherFunction())[1];
?>
Which is sad.
04-Nov-2006 12: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.
19-Oct-2006 06: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" ) ) ;
?>
24-Aug-2006 11:08
In response to the problem mentioned in the previous post (no name 06-May-2006 12:21) the following is a working solution:
$myarray = array_slice($myarray, 1, count($myarray), true);
It is too bad that the "preserve_keys" option is not available for the array_shift and array_pop functions as this would be somewhat simpler.
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.
08-Apr-2006 12:01
Array slice function that works with associative arrays (keys):
function array_slice_assoc($array,$keys) {
return array_intersect_key($array,array_flip($keys));
}
06-Sep-2005 07: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));
}
?>
28-Jul-2005 05: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));
09-Jul-2005 01: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 ;-)
...
24-Jun-2005 04: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") );
?>
07-Jun-2005 12: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;
?>
08-Dec-2004 11: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;
}
?>
18-Sep-2004 07: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;
}
05-Apr-2004 07: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
)
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'];
}
?>
22-Feb-2004 08: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
// )
?>
13-Nov-2002 02: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.
25-Apr-2002 04: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)
}
?>
03-Feb-2002 06: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.
27-Jan-2002 07: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;
}
?>
16-Dec-2001 05: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;
}
?>
