在 PHP 中用没有循环的值填充数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3506773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fill array with values without loop in PHP
提问by liysd
Is there any method (that doesn't use loop or recursion) to create and fill an array with values?
是否有任何方法(不使用循环或递归)来创建和填充数组的值?
To be precise, I want to have an effect of
准确地说,我想有一个效果
$t = array();
for($i = 0; $i < $n; $i++){
$t[] = "val";
}
But simpler.
但更简单。
回答by Sergey Eremin
回答by Frxstrem
I think you can use
我想你可以用
$array = array_pad(array(), $n, "val");
to get the desired effect.
以获得想要的效果。
See array_pad()on php.net
请参阅php.net 上的array_pad()
回答by Cooleronline
$a = array('key1'=>'some value', 'KEY_20'=>0,'anotherKey'=>0xC0DEBABE);
/* we need to nullify whole array with keep safe keys*/
/* 我们需要用保持安全的键来使整个数组无效 */
$a = array_fill_keys(array_keys($a),NULL);
var_export($a);
/*result:
array(
'key1'=>NULL,
'KEY_20'=>NULL,
'anotherKey'=>NULL
);
*/
回答by Chris
$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";
you get the idea
你明白了
回答by Stephen
It depends what you mean. There are functions to fill arrays, but they will all use loops behind the scenes. Assuming you are just looking to avoid loops in yourcode, you could use array_fill:
这取决于你的意思。有填充数组的函数,但它们都将在幕后使用循环。假设你只是希望避免循环在你的代码,你可以使用array_fill:
// Syntax: array_fill(start index, number of values; the value to fill in);
$t = array_fill(0, $n, 'val');
I.e.
IE
<?php
$t = array_fill(0, 10, 'val');
print_r($t);
?>
Will give:
会给:
Array (
[0] => val
[1] => val
[2] => val
[3] => val
[4] => val
[5] => val
[6] => val
[7] => val
[8] => val
[9] => val
)
回答by Sher Singh
<?php
$keys = array('foo', 5, 10, 'bar');
$a = array_fill_keys($keys, 'banana');
print_r($a);
?>
The above example will output:
上面的例子将输出:
Array
(
[foo] => banana
[5] => banana
[10] => banana
[bar] => banana
)