|
|
array_splice (PHP 4, PHP 5) array_splice --
Удалить последовательность элементов массива и заменить её другой последовательностью
Оисаниеarray array_splice ( array &input, int offset [, int length [, array replacement]] )
array_splice() удаляет length элементов,
расположенных на растоянии offset от начала
массива input, и заменяет их элементами
массива replacement, если он передан в качестве параметра.
Возвращает массив выбранных элементов.
Если параметр offset положителен, будут удалены элементы,
находящиеся на расстоянии offset от начала array. Если
offset отрицателен, будут удалены элементы,
находящиеся на расстоянии offset от конца array.
Если параметр length опущен, будут удалены все элементы
начиная с позиции offset и до конца массива.
Если передан положительный параметр length,
будет удалено length элементов.
Если передан отрицательный параметр length,
будут удалены элементы исходного массива, начиная с позиции offset
и заканчивая позицией, отстоящей на length элементов от конца array.
Совет: для того, чтобы удалить все элементы массива, начиная с позиции
offset в то время как указан параметр
replacement, используйте
count($input) в качестве параметра
length.
Если передан массив replacement в качестве аргумента, тогда
удалённые элементы будут заменены элементами этого массива.
Если параметры offset и
length таковы, что из исходного массива не будет ничего удалено,
тогда элементы массива replacement
будут вставлены на позицию offset.
Обратите внимание, что ключи массива replacement не сохраняются.
Совет: если вам нужно вставить
один элемент в массив, нет необходимости заключать его в вызов функции array(),
если только этот элемент не является массивом.
Последующие выражения произведут одинаковые
изменения в массиве $input:
Таблица 1. Эквиваленты array_splice() |
array_push($input, $x, $y)
|
array_splice($input, count($input), 0, array($x, $y))
| |
array_pop($input)
|
array_splice($input, -1)
| |
array_shift($input)
|
array_splice($input, 0, 1)
| |
array_unshift($input, $x, $y)
|
array_splice($input, 0, 0, array($x, $y))
| |
$input[$x] = $y // в случае, если key равен offset
|
array_splice($input, $x, 1, $y)
|
Возвращает массив, содержащий удалённые элементы.
Пример 1. Примеры использования array_splice() |
<?php
$input = array("red", "green", "blue", "yellow");
array_splice($input, 2);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, -1);
$input = array("red", "green", "blue", "yellow");
array_splice($input, 1, count($input), "orange");
$input = array("red", "green", "blue", "yellow");
array_splice($input, -1, 1, array("black", "maroon"));
$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
?>
|
|
См. также array_slice(),
unset() и
array_merge().
saurabhmdh at yahoo dot co dot on
15-Sep-2007 12:29
for inserting array in 2-d array, according x position, y position
function add_module_xy($x_loc, $y_loc, $module) {
//identify the column of the modules
switch ($x_loc) {
case 1:
$x = 'left';
break;
case 2:
$x = 'middle';
break;
case 3:
$x = 'right';
break;
default:
throw new Exception("", "Invalid horizontal position $x_loc");
}
$max_y_loc = count($this->module_arrays[$x]) + 1;
if ($y_loc > $max_y_loc) {
//if y location is greater then max array index then add module to last
$y_loc = $max_y_loc;
}
$left = array_slice ($this->module_arrays[$x], 0, $y_loc-1);
$right = array_slice ($this->module_arrays[$x], $y_loc-1);
$insert[0] = $module;
$array = array_merge ($left, $insert, $right);
$this->module_arrays[$x] = $array;
}
php barryhunter co uk
21-Mar-2007 06:01
Following on from weikard's function here is a slight variation that accepts a key in the associative array to insert the new array after, instead of simply an index.
<?php
function array_insert(&$array, $position, $insert_array) {
if (!is_int($position)) {
$i = 0;
foreach ($array as $key => $value) {
if ($key == $position) {
$position = $i;
break;
}
$i++;
}
}
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
?>
mip at ycn dot com
08-Mar-2007 05:37
Ever wounder what array_splice is doing to your references, then try this little script and see the output.
<?php
$a = "a";
$b = "b";
$c = "c";
$d = "d";
$arr = array();
$arr[] =& $a;
$arr[] =& $b;
$arr[] =& $c;
array_splice($arr,1,0,array($d));
$sec_arr = array();
$sec_arr[] =& $d;
array_splice($arr,1,0,$sec_arr);
$arr[0] = "test"; $arr[3] = "test2"; $arr[1] = "this be d?"; $arr[2] = "or this be d?"; var_dump($arr);
var_dump($a);
var_dump($b);
var_dump($d);
?>
The output will be (PHP 4.3.3):
array(5) {
[0]=>
&string(4) "test"
[1]=>
&string(10) "this be d?"
[2]=>
string(13) "or this be d?"
[3]=>
&string(5) "test2"
[4]=>
&string(1) "c"
}
string(4) "test"
string(5) "test2"
string(10) "this be d?"
So array_splice is reference safe, but you have to be careful about the generation of the replacement array.
have fun, cheers!
08-Mar-2007 03:58
<?
class _test
{
public $first='test::1';
public $second='test::2';
}
$array=array(1,2,3,4,5);
echo '<pre>',var_Dump($array),'</pre>';
/* output:
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
*/
array_Splice($array,3,0,new _test);
echo '<pre>',var_Dump($array),'</pre>';
/* output:
array(7) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
string(7) "test::1"
[4]=>
string(7) "test::2"
[5]=>
int(4)
[6]=>
int(5)
}
*/
?>
lesson: array_Splice (and maybe more others functions) takes objects like arrays
advice: close object in array
<?array_Splice($array,$x,0,array($object))?>
ahigerd at stratitec dot com
24-Jan-2007 06:07
A comment on array_merge mentioned that array_splice is faster than array_merge for inserting values. This may be the case, but if your goal is instead to reindex a numeric array, array_values() is the function of choice. Performing the following functions in a 100,000-iteration loop gave me the following times: ($b is a 3-element array)
array_splice($b, count($b)) => 0.410652
$b = array_splice($b, 0) => 0.272513
array_splice($b, 3) => 0.26529
$b = array_merge($b) => 0.233582
$b = array_values($b) => 0.151298
bdjumakov at gmail dot com
31-Aug-2006 12:11
Someone might find this function usefull. It just takes a given element from the array and moves it before given element into the same array.
<?php
function array_move($which, $where, $array)
{
$tmp = array_splice($array, $which, 1);
array_splice($array, $where, 0, $tmp);
return $array;
}
?>
Paul
11-Feb-2006 10:06
In PHP 4.3.10, at least, it seems that elements that are inserted as part of the replacement array are inserted BY REFERENCE (that is, as though with the =& rather than = assignment operation). So if your replacement array contains elements that references to variables that you can also access via other variable name, then this will be true of the elements in the final array too.
In particular, this means that it is safe to use array_splice() on arrays of objects, as you won't be creating copies of the objects (as it is so easy to do in PHP 4).
gerry-03 at 4warding dot com
09-Feb-2006 07:35
For anybody who is wondering... jrhardytwothousandtwo's trick for inserting an element using array_splice, will also work with multi-dimensional arrays if you do the following:
<?php
function array_insert(&$input, $offset, $replacement){
array_splice($input, $offset, 0, 0);
$input[$offset] = $replacement;
}
?>
I'm not sure if this (or a derivative of it) will solve other problems that I have seen just about everybody on here trying to solve. But apart from it's hackish nature, it works well for me.
ajd at cloudiness dot com
06-Dec-2005 06:35
weikard's function below is useful but it will still strip keys from array elements where the key is an integer, whether or not it is in a string:
<?php
function array_insert (&$array, $position, $insert_array) {
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
$f = array("three" => "zzz", "3" => "yyy");
$a = array("4.0" => "zzzz", "four" => "yyyy");
array_insert($a,0,$f);
var_dump($a);
?>
Julien PACHET
03-Dec-2005 06:03
If you want to remove an item of the array, shifting the others values, you can use:
function my_array_unset($array,$index) {
// unset $array[$index], shifting others values
$res=array();
$i=0;
foreach ($array as $item) {
if ($i!=$index)
$res[]=$item;
$i++;
}
return $res;
}
weikard at gmx dot de
15-Sep-2005 05:53
You cannot insert with array_splice an array with your own key. array_splice will always insert it with the key "0".
[DATA]
$test_array = array (
row1 => array (col1 => 'foobar!', col2 => 'foobar!'),
row2 => array (col1 => 'foobar!', col2 => 'foobar!'),
row3 => array (col1 => 'foobar!', col2 => 'foobar!')
);
[ACTION]
array_splice ($test_array, 2, 0, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
[RESULT]
Array (
[row1] => Array (
[col1] => foobar!
[col2] => foobar!
)
[row2] => Array (
[col1] => foobar!
[col2] => foobar!
)
[0] => Array (
[colX] => foobar2
)
[row3] => Array (
[col1] => foobar!
[col2] => foobar!
)
)
But you can use the following function:
function array_insert (&$array, $position, $insert_array) {
$first_array = array_splice ($array, 0, $position);
$array = array_merge ($first_array, $insert_array, $array);
}
[ACTION]
array_insert ($test_array, 2, array ('rowX' => array ('colX' => 'foobar2')));
echo '<pre>'; print_r ($test_array); echo '</pre>';
[RESULT]
Array (
[row1] => Array (
[col1] => foobar!
[col2] => foobar!
)
[row2] => Array (
[col1] => foobar!
[col2] => foobar!
)
[rowX] => Array (
[colX] => foobar2
)
[row3] => Array (
[col1] => foobar!
[col2] => foobar!
)
)
[NOTE]
The position "0" will insert the array in the first position (like array_shift). If you try a position higher than the langth of the array, you add it to the array like the function array_push.
cronodragon_at_gmail
13-Sep-2005 06:54
To delete an element of an array just use unset(). Example:
// Deletes the element with the key "quux" from array $bar
unset($bar['quux']);
Easy! =)
csaba at alum dot mit dot edu
13-Aug-2005 02:31
Appending arrays
If you have an array $a2 whose values you would like to append to an array $a1 then four methods you could use are listed below in order of increasing time. The last two methods took significantly more time than the first two. The most surprising lesson is that using the & incurs a time hit.
foreach ($a2 as $elem) $a1[]=$elem;
foreach ($a2 as &$elem) $a1[]=$elem;
array_splice ($a1, count($a1), 0, $a2);
$a1 = array_merge($a1, $a2);
Csaba Gabor from Vienna
randomdestination at gmail dot com
22-Jul-2005 01:52
To split an associative array based on it's keys, use this function:
<?php
function &array_split(&$in) {
$keys = func_get_args();
array_shift($keys);
$out = array();
foreach($keys as $key) {
if(isset($in[$key]))
$out[$key] = $in[$key];
else
$out[$key] = null;
unset($in[$key]);
}
return $out;
}
?>
Example:
<?php
$testin = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$testout =& array_split($testin, 'a', 'b', 'c');
print_r($testin);
print_r($testout);
?>
Will print:
Array
(
[d] => 4
)
Array
(
[a] => 1
[b] => 2
[c] => 3
)
Hope this helps anyone!
fontajos at phpeppershop dot com
15-Apr-2005 07:48
<?php
function delArrayElementByKey($array_with_elements, $key_name) {
$key_index = array_keys(array_keys($array_with_elements), $key_name);
if (count($key_index) != '') {
array_splice($array_with_elements, $key_index[0], 1);
}
return $array_with_elements;
}?>
gideon at i6developments dot com
17-Jul-2004 09:45
array_splice dynamically updates the total number of entries into the array. So for instance I had a case where I needed to insert a value into every 4th entry of the array from the back. The problem was when it added the first, because the total number was dynamically updated, it would only add after the 3rd then the 2nd and so one. The solution I found is to track the number of inserts which were done and account for them dynamically.
Code:
<?php
$modarray = array_reverse($mili);
$trig=1;
foreach($modarray as $rubber => $glue) {
if($rubber!="<BR>") {
$i++;
$b++;
if ($i==4) {
$trig++;
if($trig<=2) {
array_splice($modarray,$b,0,"<BR>");
}elseif($trig>=3){
array_splice($modarray,$b+($trig-2),0,"<BR>");
}
$i=0;
};
};
};
$fixarray = array_reverse($modarray);
?>
jtgt at gmx dot de (Richard Lachmann)
16-Jul-2004 09:18
This function will preserve keys:
<?php
function my_array_splice(&$_arr, $_index, $_long){
$_keys=array_keys($_arr);
$_key=array_search($_index, $_keys);
if ( $_key !== FALSE ){
$_keys=array_splice($_keys, $_key, $_long);
foreach ($_keys as $_key) unset($_arr[$_key]);
}
}
?>
reverse esacdaehasinhoj at oohay dot moc
28-Jun-2004 04:15
Also, a quick function to discard empty entries in an array which otherwise keeps keys intact:
<?php
function remove_empty($inarray) {
if (is_array($inarray)) {
foreach($inarray as $k=>$v) {
if (!(empty($v))) {
$out[$k]=$v;
}
}
return $out;
} else {
return $inarray;
}
}
print_r(remove_empty(array('', 'foo', '', 'bar', '', '', 'baz', '')));
?>
Should return:
Array
(
[1] => foo
[3] => bar
[6] => baz
)
cyril carrez
29-May-2004 08:19
array_splice does work when replacing with objects. As stated in the manual, you have to embed the object in an array:
<?php
array_splice ($myarray, $offset, 0, Array($myobjet));
?>
rolandfoxx at yahoo dot com
30-Mar-2004 12:16
Be careful, array_splice does not behave like you might expect should you try to pass it an object as the replacement argument. Consider the following:
<?php
class Tree {
var $childNodes
function addChild($offset, $node) {
array_splice($this->childNodes, $offset, 0, $node);
}
}
class Node {
var $stuff
...
}
$tree = new Tree();
echo (count($tree->childNodes)); $newNode = new Node();
$tree->addChild(1, $newNode);
echo(count($tree->childNodes)); ?>
In this case, the array has a number of items added to it equal to the number of attributes in the new Node object and the values thereof I.e, if your Node object has 2 attributes with values "foo" and "bar", count($tree->childNodes) will now return 4, with the items "foo" and "bar" added to it. I'm not sure if this qualifies as a bug, or is just a byproduct of how PHP handles objects.
Here's a workaround for this problem:
function array_insertobj(&$array, $offset, $insert) {
$firstPart = array_slice($array, 0, $offset);
$secondPart = array_slice($array, $offset);
$insertPart = array($insert);
$array = array_merge($firstPart, $insertPart, $secondPart);
}
Note that this function makes no allowances for when $offset equals the first or last index in the array. That's because array_unshift and array_push work just fine in those cases. It's only array_splice that can trip you up. Obviously, this is kinda tailor-made for arrays with numeric keys when you don't really care what said keys are, but i'm sure you could adapt it for associative arrays if you needed it.
bitmor.co.kr
19-Feb-2004 04:30
//orginal
IndexKey Bad Police
richard at richard-sumilang dot com
23-Nov-2002 04:27
<?php
function array_slice2($array, $val, $slice="name"){
switch($slice){
case "name":
while(list($i,$k)=each($array)){
if( $i != $val) { $return[$i]=$array[$i]; print "i = $i,val = $val<br>";}
else print " exit BugShow i = $i,val = $val <br>";
}
break;
case "variable":
while(list($i)=each($array)){
if($array[$i]!=$val) $return[$i]=$array[$i];
}
break;
}
return $return;
}
$list = array( "0" => "zero", "1" => "one", "2" => "two", "3" => "three", "4" => "four", "5" => "five", "6" => "six");
print_r( array_slice2 ( $list,'tne') );echo "<br>";
?>
<?php
print_r( array_slice2 ( $list,"one","variable") );echo "<br>";
?>
//
michael at cannonbose dot com
05-Feb-2004 02:16
While trying to find a way to insert some array into another at some index, array_splice seemed like the function that I wanted. The results weren't quite as expected though. Of course, I can be using it wrong.
My desired results turned out be $array1 after calling array_splice() and no tuning got me to have $array3 with what was showing up in $array1.
[code]
<?php
$array1 = array(1, 2, 3, 7, 8, 9);
$array2 = array(4, 5, 6);
echo '<br />array1 :: ';
print_r( $array1 );
echo '<br />array2 :: ';
print_r( $array2 );
$index = 3;
$length = 0;
$array3 = array_splice($array1, $index, $length,
$array2);
echo '<br />array1 :: ';
print_r( $array1 );
echo '<br />array2 :: ';
print_r( $array2 );
echo '<br />array3 :: ';
print_r( $array3 );
?>
[/code]
Results in
[code]
array1 :: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 7 [4] => 8 [5] => 9 )
array2 :: Array ( [0] => 4 [1] => 5 [2] => 6 )
array1 :: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 )
array2 :: Array ( [0] => 4 [1] => 5 [2] => 6 )
array3 :: Array ( )
[/code]
Cheers,
Michael
roeltje.com
03-Nov-2003 11:56
In reply on the message "18-Aug-2003 09:57"
If you want to insert a value into some array
<?
// I think we can replace
array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3)));
// with for inserting multiple values
array_splice($array, 3, 0, array('x','y'));
// or for just inserting 1 value
array_splice($array, 3, 0, 'x');
?>
Sounds to me a lot faster.
Roeltje...
|