(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
array_fill
— 用给定的值填充数组
array_fill(int $start_index, int $count, mixed $value): array
用 value
参数的值填充 count
个元素到数组, 开始键名由 start_index
参数指定。
start_index
返回的数组的第一个索引值。
如果 start_index
是负数,在 PHP 8.0.0 之前,返回的数组的第一个索引是 start_index, 而后面索引则从 0 开始;自 PHP 8.0.0 起, 负数键将会正常递增。
count
要插入元素的数量。必须大于或等于 0 且小于或等于 2147483647。
value
用来填充的值。
返回填充后的数组。
如果 count
超出范围,将会抛出 ValueError
。
版本 | 说明 |
8.0.0 | 如果 array_fill() 的 count 超出范围现在将会抛出 ValueError, 之前会引发 E_WARNING 且函数返回 false 。 |
实例1:
$a = array_fill(5, 6, 'banana');
dump($a);
// 输出
array(6) {
[5] => string(6) "banana"
[6] => string(6) "banana"
[7] => string(6) "banana"
[8] => string(6) "banana"
[9] => string(6) "banana"
[10] => string(6) "banana"
}
实例2:开始索引为负数的 array_fill() 示例
$a = array_fill(-2, 4, 'pear');
dump($a);
// 以上示例在 PHP 7 中的输出:
array(4) {
[-2] => string(4) "pear"
[0] => string(4) "pear"
[1] => string(4) "pear"
[2] => string(4) "pear"
}
// 以上示例在 PHP 8 中的输出:
Array(
[-2] => pear
[-1] => pear
[0] => pear
[1] => pear
)
注意 索引 -1 在 PHP 8.0.0 之前不存在
实例3:快速创建一个(10X10)的数组
$a = array_fill(0, 10, array_fill(0, 10, 0));
dump($a);
// 输出
array(10) {
[0] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[1] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[2] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[3] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[4] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[5] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[6] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[7] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[8] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
[9] => array(10) {
[0] => int(0)
[1] => int(0)
[2] => int(0)
[3] => int(0)
[4] => int(0)
[5] => int(0)
[6] => int(0)
[7] => int(0)
[8] => int(0)
[9] => int(0)
}
}
2023-07-25 更新