How to combine the same array multiple times?

I would like to ask for help with this simple task. Say I have one array('a', 'b', 'c'). What I want is to combine the exact same array several times into the same or a new empty array. For example, a 3x merge would create this:

array('a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c')

I know it exists array_merge, but how to use it if I have an optional number of times when the array should be combined? Of course, I could sing and merge:

$new = array();
for ($i=0; $i < $howManyTimes; $i++) {
    $new = array_merge($new, array('a', 'b', 'c'));
}

Or I could use hack, juggle between strings and arrays:

$new = str_split(str_repeat(implode('', array('a', 'b', 'c')), $howManyTimes));

However, none of these approaches feels good, so I would appreciate any ideas and other / better ways to do what I need in PHP (5).

Thank!

EDIT: @Amal Murali, , . , , . 10 000 :

  • array_merge() 37
  • array to string to array 7 !!

, array_merge, , , .

, ;)

+4
2

""

, array_merge() PHP . ? , , : -. PHP - hashtables, .

, , "" . , , - array_merge(). - , . , - "" "" .

array_merge()

, array_merge() . , N , N - . , , , array_merge() (- -).

, :

function repeatMerge($array, $rCount)
{
    return call_user_func_array('array_merge', array_fill(1, $rCount, $array));
}

, array_walk()? array_merge() : , - . , - . , ( )

- array_merge() . :

function repeatLoops($array, $rCount)
{
    $result = [];
    $eCount = count($array);
    for($j=0; $j<$rCount; $j++)
    {
        for($i=0; $i<$eCount; $i++)
        {
           $result[]=$array[$i];
        }
    }
    return $result;
}

. . , . , , , array_merge() - -.

, ,

Benchmark . , "" ( , ), - , , , array_merge(), . tesing:

$array      = range(1, 1000);
$count      = 1000;

1E1 :

//first function (repeatMerge), 1E1=10 times
array(3) {
  [1]=>
  float(2.1156709194183)
  [2]=>
  float(0.21156709194183)
  [3]=>
  int(10)
}
//second function (repeatLoops), 1E1=10 times
array(3) {
  [1]=>
  float(1.6837940216064)
  [2]=>
  float(0.16837940216064)
  [3]=>
  int(10)
}

1E2 :

//first function (repeatMerge), 1E2=100 times
array(3) {
  [1]=>
  float(20.907063007355)
  [2]=>
  float(0.20907063007355)
  [3]=>
  int(100)
}
//second function (repeatLoops), 1E2=100 times
array(3) {
  [1]=>
  float(16.947901964188)
  [2]=>
  float(0.16947901964188)
  [3]=>
  int(100)
}

( - , , , ). ( github).

  • [1] ( ) :
  • [2] ( ) : avg.
  • [3] ( ) :
+4

. .

@alma-do repeatMerge(…):

$new = array_merge(...array_fill(0, $howManyTimes, ['a', 'b', 'c']));

. , repeatMerge(…). . , , - , , - splat PHP 5.6 .

0

Source: https://habr.com/ru/post/1544955/


All Articles