Why can't I place a variable into my array? [closed]
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);
精彩评论