Ni Le
Ni Le

Reputation: 199

Easiest way to duplicate array values right after occurence?

I want these arrays...

array('bread','jelly','olive');
array('chocolate','chip');

To become these arrays...

array('bread','bread','jelly','jelly','olive','olive');
array('chocolate','chocolate','chip','chip');

Is there an easy way to do this?

Upvotes: 1

Views: 64

Answers (5)

George Fish
George Fish

Reputation: 11

Use array_splice() Works really fast, because no sorting is involved.

$a = array('bread','jelly','olive');
$i=0;
foreach ($a as $b) {
    array_splice($a,$i*2,0,$b);
    $i++;
}

Upvotes: 1

Colin M
Colin M

Reputation: 13348

function duplicateItems(array $inputArray, $n = 2) {
    $result = array();
    foreach ($inputArray as $value) {
        for ($i = 0; $i < $n; $i++) {
            $result[] = $value;
        }
    }
    return $result;
}

Usage:

$duplicateArray = duplicateItems(array('bread', 'jelly', 'olive'));

Upvotes: 2

Ray
Ray

Reputation: 41428

If this will work: array('bread','jelly','olive',bread','jelly',''olive');

 $array = array('bread','jelly','olive');
 $array = array_merge($array, $array);

Then you could sort alphabetically:

 sort($array);

Upvotes: 0

Sammitch
Sammitch

Reputation: 32252

$myarray = array('bread','jelly','olive');
$mynewarray = array_merge($myarray, $myarray);
sort($mynewarray);
var_dump($mynewarray);

Output:

array(6) {
  [0]=>
  string(5) "bread"
  [1]=>
  string(5) "bread"
  [2]=>
  string(5) "jelly"
  [3]=>
  string(5) "jelly"
  [4]=>
  string(5) "olive"
  [5]=>
  string(5) "olive"
}

Upvotes: 2

mpaepper
mpaepper

Reputation: 4022

You could do:

$singleValues = array('bread','jelly','olive');
$newArray = array();
foreach ($singleValues as $value) {
   $newArray[] = $value;
   $newArray[] = $value;
}

Upvotes: 0

Related Questions