开发者

How to repeat an array in PHP?

开发者 https://www.devze.com 2023-01-01 20:43 出处:网络
$arr = array(\'1st\'开发者_JS百科, \'1st\'); The above $arr has 2 items , I want to repeat $arr so that it\'s populated with 4 items
$arr = array('1st'开发者_JS百科, '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?


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');


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

$arr = array_merge($arr, $arr);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消