Thursday, 30 August 2018

Creating an associative array with PHP random values

I am trying to generate an associate array with random values. For example, if I give you this string:

something, anotherThing, foo, bar, baz

(the length of the string is dynamic - so there could be 10 items, or 15);
I would like to create an array based on those values:
$random = rand();
array("something"=>$random, "anotherThing"=>$random, "foo"=>$random, "bar"=>$random, "baz"=>$random);

And it builds the array based on how many values it's given.
I know how to order them into an array like so:
explode(", ", $valueString);

But how can I assign the values to make it an associative array?
Thanks.

NOTE: I am assuming that you want each item to have a different random value (which is not exactly what happens in your example).
With PHP 5.3 or later, you can do this most easily like so:
$keys = array('something', 'anotherThing', 'foo', 'bar', 'baz');
$values = array_map(function() { return mt_rand(); }, $keys);

$result = array_combine($keys, $values);
print_r($result);

For earlier versions, or if you don't want to use array_map, you can do the same thing in a more down to earth but slightly more verbose manner:
$keys = array('something', 'anotherThing', 'foo', 'bar', 'baz');
$result = array();
foreach($keys as $key) {
    $result[$key] = mt_rand();
}

print_r($result);

0 comments:

Post a Comment