开发者

Why can't I place a variable into my array? [closed]

开发者 https://www.devze.com 2023-04-09 09:50 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. 开发者_开发问答 Closed 11 years ago.

Is it possible to have a variable in an array as a value in PHP. For example:

'arraykey' => "$varname",

It does not seem to work and I can't find any info about this anywhere. Maybe because its just not possible? Any insight is appreciated. Thanks.


Yes you can, but not using double quotes. It will cause the value of the variable to be inserted in the string instead.

Use this:

$cow = "Mooo";
$varname = 'cow';

$a = array('arrayitem' => '$varname');

$var = $a['arrayitem'];

echo $$var;

Or rather: don't use it. It won't make your code very readable. But it's possible, as you can see. :)


Do you mean:

$array['item'] = $varname;

There are lots of use-cases in the spec: http://php.net/manual/en/language.types.array.php


$array[] = $var;  
$array['item'] = $var;

Dont use $variables inside "" and ''s


It is entirely possible, but you do not need the quotes around the variable name.

$x = 1;
$y = 2;
$z = "pasta";
$myVars = array(
   'x' => $x,
   'y' => $y,
   'z' => $z
);
print_r($myVars);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号