如何在PHP中重复数组?

时间:2022-06-15 21:38:16
$arr = array('1st', '1st');

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

上面的$ arr有2个项目,我想重复$ arr,以便填充4个项目

Is there a single call in PHP?

在PHP中有一个单独的调用吗?

3 个解决方案

#1


10  

array_fill function should help:

array_fill函数应该有帮助:

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.

使用value参数值的num个条目填充数组,从start_index参数开始的键。

In your case code will look like:

在您的情况下代码将如下所示:

$arr = array_fill(0, 4, '1st');

#2


8  

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

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

#3


0  

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:

这是一个更一般的答案。在PHP 5.6+中,您可以使用“splat”运算符(...)重复数组任意次:

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

Where $n is any integer.

其中$ n是任何整数。

#1


10  

array_fill function should help:

array_fill函数应该有帮助:

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.

使用value参数值的num个条目填充数组,从start_index参数开始的键。

In your case code will look like:

在您的情况下代码将如下所示:

$arr = array_fill(0, 4, '1st');

#2


8  

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

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

#3


0  

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:

这是一个更一般的答案。在PHP 5.6+中,您可以使用“splat”运算符(...)重复数组任意次:

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

Where $n is any integer.

其中$ n是任何整数。