I need <?php array_Splice()?> function, that use array keys instead of order (offset and length) because of associated arrays, and this is result:
<?php
function array_KSplice1(&$input, $start, $end=null, $replacement=null)
{
$keys=array_Keys($input);
$values=array_Values($input);
if($replacement!==null)
{
$replacement=(array)$replacement;
$rKeys=array_Keys($replacement);
$rValues=array_Values($replacement);
}
$start=array_Search($start,$keys,true);
if($start===false)
return false;
if($end!==null)
{
$end=array_Search($end,$keys,true);
if($end===false)
return false;
if($end<$start)
return false;
$end-=$start-1;
}
if($replacement!==null)
{
array_Splice($keys,$start,$end,$rKeys);
array_Splice($values,$start,$end,$rValues);
}
else
{
array_Splice($keys,$start,$end);
array_Splice($values,$start,$end);
}
$input=array_Combine($keys,$values);
return $input;
}
function array_KSplice2(&$input, $start, $length=0, $replacement=null)
{
$keys=array_Keys($input);
$values=array_Values($input);
if($replacement!==null)
{
$replacement=(array)$replacement;
$rKeys=array_Keys($replacement);
$rValues=array_Values($replacement);
}
$start=array_Search($start,$keys,true);
if($start===false)
return false;
if($replacement!==null)
{
array_Splice($keys,$start,$length,$rKeys);
array_Splice($values,$start,$length,$rValues);
}
else
{
array_Splice($keys,$start,$length);
array_Splice($values,$start,$length);
}
$input=array_Combine($keys,$values);
return $input;
}
$array=range(1,10);
var_Dump(array_KSplice1($array,3,3,array(100=>101,102,103,104)));
$array=range(1,10);
var_Dump(array_KSplice2($array,3,3,array(100=>101,102,103,104)));
?>
Both examples output:
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[100]=>
int(101)
[101]=>
int(102)
[102]=>
int(103)
[103]=>
int(104)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
}