是否有任何方法(不使用循环或递归)来创建和填充带有值的数组?
确切地说,我希望产生
的效果$t = array();
for($i = 0; $i < $n; $i++){
$t[] = "val";
}
但更简单。
答案 0 :(得分:31)
使用array_fill()
:
$t = array_fill(0, $n, 'val');
答案 1 :(得分:3)
答案 2 :(得分:1)
$a = array();
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
$a[] = "value";
你明白了
答案 3 :(得分:1)
$a = array('key1'=>'some value', 'KEY_20'=>0,'anotherKey'=>0xC0DEBABE);
/ *我们需要使用保持安全密钥* /
来取消整个数组$a = array_fill_keys(array_keys($a),NULL);
var_export($a);
/*result:
array(
'key1'=>NULL,
'KEY_20'=>NULL,
'anotherKey'=>NULL
);
*/
答案 4 :(得分:0)
这取决于你的意思。有些函数可以填充数组,但它们都会在幕后使用循环。假设您只是想避免 代码中的循环,可以使用array_fill:
// Syntax: array_fill(start index, number of values; the value to fill in);
$t = array_fill(0, $n, 'val');
即
<?php
$t = array_fill(0, 10, 'val');
print_r($t);
?>
会给:
Array (
[0] => val
[1] => val
[2] => val
[3] => val
[4] => val
[5] => val
[6] => val
[7] => val
[8] => val
[9] => val
)
答案 5 :(得分:0)
<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>
上面的示例将输出:
Array
(
[foo] => banana
[5] => banana
[10] => banana
[bar] => banana
)