2

With array_fill, I want to repeat and merge array.

Example, when I execute :

$array = array_fill(0, 2, array_merge(
   ['hello'],
   ['by']
));

var_dump($array);

I have this result :

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
  [1]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
  }
}

But I want this result :

array(4) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(2) "by"
    [2]=>
    string(5) "hello"
    [3]=>
    string(2) "by"
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
Gaylord.P
  • 1,539
  • 2
  • 24
  • 54

3 Answers3

2

There are many ways to do this but it's a good opportunity to show how you can do this with various PHP iterators including ArrayIterator, InfiniteIterator and LimitIterator; e.g:

// create an ArrayIterator with the values you want to cycle
$values = new ArrayIterator(['hello', 'by']);
// wrap it in an InfiniteIterator to cycle over the values
$cycle  = new InfiniteIterator($values);
// wrap that in a LimitIterator defining a max of four iterations
$limit  = new LimitIterator($cycle,0, 4);


// then you can simply foreach over the values 
$array = [];

foreach ($limit as $value) {
  $array[] = $value;
}

var_dump($array);

Yields:

array(4) {
  [0]=>
  string(5) "hello"
  [1]=>
  string(2) "by"
  [2]=>
  string(5) "hello"
  [3]=>
  string(2) "by"
}

Hope this helps :)

Darragh Enright
  • 13,676
  • 7
  • 41
  • 48
2

Add one more step - merge all these arrays into one:

$array = array_merge(...array_fill(0, 2, array_merge(
   ['hello'],
   ['by']
)));

Here I used a variadic function argument syntax. If your php version (older than php5.6) doesn't support it, use call_user_func_array:

$array = call_user_func_array('array_merge', array_fill(0, 2, array_merge(
   ['hello'],
   ['by']
)));
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

You can use the flatten function, which will process the result of your code.

function flatten(array $ar) {
    $r = array();
    array_walk_recursive($ar, function($a) use (&$r) { $r[] = $a; });
    return $r;
}

$array = flatten(
    array_fill(0, 2, array_merge(
        ['hello'],
        ['by']
    ))
);

var_dump($array);

Result:

array(4) { 
    [0]=> string(5) "hello" 
    [1]=> string(2) "by" 
    [2]=> string(5) "hello" 
    [3]=> string(2) "by" 
}
Artee
  • 824
  • 9
  • 19