在PHP中,数组函数 array_fill () 用于使用给定的值填充数组。
函数语法:
array_fill ( int $start_index , int $num , mixed $value ) : array
函数参数说明:
参数 | 描述 |
---|---|
start_index | 必需。规定返回数组的起始索引。 |
num | 必需。规定填充的元素的数量,其值必须大于 0。 |
value | 必需。规定用于填充数组的键值。 |
array_fill() 函数使用给定的参数 value 值填充一个数组,数组的元素个数为参数 num 指定的数量,数组的键由 start_index 参数指定的索引开始。
举例1,填充数组(开始索引大于等于0):
<?php // 填充数组 $res = array_fill(0, 4, 'h'); var_dump($res);
以上代码输出如下:
array (size=4) 0 => string 'h' (length=1) 1 => string 'h' (length=1) 2 => string 'h' (length=1) 3 => string 'h' (length=1)
举例2,填充数组(开始索引小于0):
<?php // 填充数组 $res = array_fill(-2, 4, 'h'); var_dump($res);
以上代码输出如下:
array (size=4) -2 => string 'h' (length=1) 0 => string 'h' (length=1) 1 => string 'h' (length=1) 2 => string 'h' (length=1)
注意:
生成的数组的键索引 start_index 可以是正式或负数,如果是正数,则索引从指定的值开始增加;如果 start_index 是负数, 那么返回的数组的第一个索引将会是 start_index ,后面的索引则从0开始。