简体   繁体   中英

PHP: How to dynamically assign variables into array

This is killing me, for the life of me i can not seem to figure out how to get this to work, or why it doesn't work in the first place.

Here is what i'm trying to do:

here is my variables declaration:

$locale = 'US';
$realm = 'magtheridon';
$character = 'billymayys';

here is my array declaration:

$my_array = ( 'L' => $locale, 'R' => $realm, 'C' => $character );

I am new to php and from what i can tell this should create an array who would print out to:

Array( 
      [L] => US, 
      [R] => magtheridon, 
      [C] => billymayys, 
      );

But it doesn't.

What is the proper way to create an array, whos index i can name and then assign variables to the values of those indexs?

The array declaration:

$my_array = ( 'L' => 'US', 'R' => 'magtheridon', 'C' => 'billymayys' );

Works but i do not understand why i cannot dynamically assign the values using variables.

Please help! Thanks.

You just have a minor syntax error, missing the array keyword.

Change:

$my_array = ( 'L' => $locale, 'R' => $realm, 'C' => $character );

To:

$my_array = array( 'L' => $locale, 'R' => $realm, 'C' => $character );

Or:

$my_array = [ 'L' => $locale, 'R' => $realm, 'C' => $character ]; // PHP 5.4+

Working example: http://3v4l.org/d2UWM

You need to use the array keyword:

$my_array = array( 'L' => $locale, 'R' => $realm, 'C' => $character );

Not sure why the second one would work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM