How do I use environment variables ( to create an array?


If you’re not aware of this, environment variables are kind of like secret values in as makes your code publicly available for everybody.

I have a set of keys that I want to remain hidden on the website, and I want the website to randomize a key selection to distribute to the user on page load. Kind of a makeshift key system.

However, once I put the key values into the environment variable, and I try to load it into an array, this happens:

This, in basis, is the code I’m using (I load the varaible $trollitem for display later on in the code, but that’s just a bunch of HTML design)

  $loadstring = getenv('cheatxkeys');
  $items = array($loadstring);
  $trollitem = $items[array_rand($items)];

And finally, this is how my environment variable looks:

For obvious reasons, these are not the actual key codes I’m using, but rather a randomly generated amount of key codes to show what I’m trying to do.

If my post is unclear, please just comment, I really want to get this to work properly. Thanks!


Your environment variable $loadstring is stored and retrieved as a string, and PHP array() takes as parameters all the elements of the array to be created. Therefore, array($loadstring) gives an array of length 1 with the full string stored in the environment variable as its only element.

It appears your string format is like a JSON array, but without the enclosing square brackets, so you can do this:

$items = json_decode('[' . $loadstring . ']');

See also the json_decode documentation.

Answered By – Lionel Rowe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published