How do I insert a variable into a PHP array?

﹥>﹥吖頭↗ 提交于 2020-01-12 14:22:12

问题


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?


回答1:


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.




回答2:


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];



回答3:


Yes, you can store variables within arrays, though you'll need to remove the space between $result and the opening bracket.

$foo = $result["bar"]; // assuming value of 'bar'

$collection = array( $foo, "fizz" );

foreach ( $collection as $item ) {
  // bar, fizz
  echo $item;
}


来源:https://stackoverflow.com/questions/10425712/how-do-i-insert-a-variable-into-a-php-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!