'How to duplicate an element in a php array after it current position
Hi I was wondering how I could duplicate an element in a php array x times. In such a way that the clones come after the original. If this is your original array.
array(
[0]=>'Clone me please',
[1]=>'I m here for decoration'
)
Resulting in :
array(
[0]=>'Clone me please',
[1]=>'Clone me please',
[2]=>'Clone me please',
[3]=>'I m here for decoration'
)
Thanks in advance.
Solution 1:[1]
I first built a function to loop through the number of times you want to clone your element .. And I made a function that will insert the clone after the desired key .. It's an amalgamation of two functions I had already built for different purposes ..
<?php
$array = array();
$array[0] = 'Clone Me Please';
$array[1] = 'Clone Me Too Please';
$array[2] = 'I am here for decoration';
print_r ( cloneItem(0,$array,3) );
print_r ( cloneItem(1,$array,2) );
function cloneItem($itemKey, $array, $timesToDuplicate){
$clone_me[0] = $array[$itemKey];
for ($x = 1; $x <= $timesToDuplicate; $x++){
$array = array_insert_after($array,$itemKey,$clone_me);
}
return $array;
}
function array_insert_after( $array, $key, $new ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys );
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}
Output ..
Array
(
[0] => Clone Me Please
[1] => Clone Me Please
[2] => Clone Me Please
[3] => Clone Me Please
[4] => Clone Me Too Please
[5] => I am here for decoration
)
Array
(
[0] => Clone Me Please
[1] => Clone Me Too Please
[2] => Clone Me Too Please
[3] => Clone Me Too Please
[4] => I am here for decoration
)
Solution 2:[2]
Here's a simple function using a few php array functions.
function dupeElement(int $position, int $count, array $orig): array {
$mid = array_fill(0, $count, $orig[$position]);
$end = array_slice($orig, $position + 1);
array_splice($orig, ++$position);
return array_merge($orig, $mid, $end);
}
- array_fill is used to create a new array, based on the index location of the element you want to dupe in the original array
- array_slice is used to get the portion after the element you want to duplicate
- array_splice in this function is used to remove the end portion of the array.
- array_merge lets you merge numeric arrays in the order you provide them.
The $position param should be the exact numeric index of the item to be duped (0 based). The $count is the number of duplications you want. The final array will be $count + 1 of the items (as it includes the original).
For your example, assuming your array was named $a:
$a = dupeElement(0, 2, $a);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zak |
| Solution 2 |
