如何将变量插入到 PHP 数组中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10425712/
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
How do I insert a variable into a PHP array?
提问by Norm
I have looked for some responses on the web, but none of them are very accurate.
我在网上找了一些答案,但没有一个是非常准确的。
I want to be able to do this:
我希望能够做到这一点:
$id = "" . $result ["id"] . "";
$info = array('$id','Example');
echo $info[0];
Is this possible in any way?
这有可能吗?
回答by codaddict
What you need is (not recommended):
您需要的是(不推荐):
$info = array("$id",'Example'); // variable interpolation happens in ""
or just
要不就
$info = array($id,'Example'); // directly use the variable, no quotes needed
You've enclosed the variable inside single quotes and inside single quotes variable interpolation does not happen and '$id'is treated as a string of length three where the first character is a dollar.
您已将变量括在单引号内,单引号内的变量插值不会发生,并且'$id'被视为长度为 3 的字符串,其中第一个字符是美元。
回答by icktoofay
Just don't put it in quotes:
只是不要把它放在引号中:
$id = $result["id"];
$info = array($id, 'Example');
echo $info[0];
Alternatively, if you use double quotes rather than single quotes, then it will be interpolated (which also results in it being converted to a string):
或者,如果您使用双引号而不是单引号,那么它将被插入(这也会导致它被转换为字符串):
$id = $result["id"];
$info = array("$id", 'Example');
echo $info[0];
回答by Sampson
Yes, you can store variables within arrays, though you'll need to remove the space between $resultand the opening bracket.
是的,您可以在数组中存储变量,但您需要删除$result左括号和左括号之间的空格。
$foo = $result["bar"]; // assuming value of 'bar'
$collection = array( $foo, "fizz" );
foreach ( $collection as $item ) {
// bar, fizz
echo $item;
}

