Page 1 of 1

Variable expansion inside associative array definition

Posted: 26 Sep 2023 12:45
by jaywalker32
Is there a way to make the script get the value of $dogname in the following script?

Code: Select all

  $dogname = "rex";
  $name = array("cat" => "pussy", "dog" => $dogname); echo $name["dog"];
Expected:

Code: Select all

rex
Actual:

Code: Select all

$dogname

Re: Variable expansion inside associative array definition

Posted: 26 Sep 2023 13:06
by PeterH
Wasn't it so that array() defines to not allow/support variables?

Re: Variable expansion inside associative array definition

Posted: 26 Sep 2023 13:23
by highend
Special Function array()
There is a special function array() to populate arrays. Non-existing arrays are created, dimensioned and populated, existing arrays are redimensioned and overwritten.
$a = array("cat", "dog"); echo $a[0]; $a = array("dog"); echo $a[0]; //cat, dog
Notes:
ยท
You can only pass literal strings as values, not variables. Values are separated by commas.