Variable expansion inside associative array definition

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
jaywalker32
Posts: 205
Joined: 27 May 2014 05:24

Variable expansion inside associative array definition

Post 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

PeterH
Posts: 2785
Joined: 21 Nov 2005 20:39
Location: Germany

Re: Variable expansion inside associative array definition

Post by PeterH »

Wasn't it so that array() defines to not allow/support variables?
Win11 Pro 223H2 Gerrman

highend
Posts: 13336
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: Variable expansion inside associative array definition

Post 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.
One of my scripts helped you out? Please donate via Paypal

Post Reply