13
$arr = array('1st', '1st');

The above $arr has 2 items , I want to repeat $arr so that it's populated with 4 items

Is there a single call in PHP?

wamp
  • 5,789
  • 17
  • 52
  • 82

3 Answers3

24

array_fill function should help:

array array_fill ( int $start_index, int $num, mixed $value )

Fills an array with num entries of the value of the value parameter, keys starting at the start_index parameter.

In your case code will look like:

$arr = array_fill(0, 4, '1st');
Jonas
  • 2,910
  • 2
  • 26
  • 36
11

This is a more general answer. In PHP 5.6+ you can use the "splat" operator (...) to repeat the array an arbitrary number of times:

array_merge(...array_fill(0, $n, $arr));

Where $n is any integer.

acobster
  • 1,637
  • 4
  • 17
  • 32
10
$arr = array('1st', '1st');

$arr = array_merge($arr, $arr);
Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • I think this is better because I don't need to bother with the indexes. – wamp Jun 03 '10 at 06:48
  • 1
    It depends on what do you want to express. If you have an array with some values and you want to double them - use array_merge, and if you want to have an array with predefined number of the same values, then use array_fill. In coding it's not all about you (what is easier for you) it's about easiness to read and understand the code. – Jonas Jun 03 '10 at 06:55
  • `$arr + $arr` is also a valid option. The main difference between '+' array operator and `array_merge` is the order when overriding values with the same key. – s3c Sep 20 '22 at 10:18