Home > OS >  How do I use environment variables (repl.it) to create an array?
How do I use environment variables (repl.it) to create an array?

Time:06-14

If you're not aware of this, environment variables are kind of like secret values in Repl.it as Repl.it 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: https://i.imgur.com/sNFsdb6.png

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)

<?php
  $loadstring = getenv('cheatxkeys');
  $items = array($loadstring);
  $trollitem = $items[array_rand($items)];
?>

And finally, this is how my environment variable looks: https://i.imgur.com/qaCZxOU.png

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!

CodePudding user response:

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.

  • Related