array_slice

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 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 that array_slice() will reorder and reset the
numeric array indices by default. You can change this behaviour by setting
preserve_keys to TRUE.

Return Values

Returns the slice. If the offset is larger than the size of the array then returns an empty array.

Changelog

Version

Description

5.2.4

The default value of the length parameter was changed to NULL. A NULLlength now tells the function to use the length of array. Prior to this version, a NULLlength was taken to mean a zero length (nothing will be returned).

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.

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 contentsprint_r($newarray). "<br>"; //print the new empty array

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.

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 )

<?php// Combines two arrays by inserting one into the other at a given position then returns the resultfunction 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)); }?>

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.

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.

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:

By combining this with str_split() and implode(),slices can also be excerpted from strings with the following simple function:<?phpfunction 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);};?>

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.

[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;

'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.

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.