2

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.

3 Answers3

7

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);
Jon
  • 428,835
  • 81
  • 738
  • 806
2

all example are good, but not simple

  1. Init array

    $arr = array();
    
  2. How many values your need?

    $m = 10;
    
  3. save random to all elements of array

    for ($i=0;$i<$m;$i++)
    {
       $arr[$i] = mt_rand();
    }
    

Why make more complex this simple example?

, Arsen

publikz.com
  • 931
  • 1
  • 12
  • 22
1

I suppose you have the keys in $key_array. This will make $random the value of each key:

$random = rand();
$array = array_fill_keys($key_array, $random);

If you need a way to apply different random values to each element, here's one (of several) solutions:

$array = array_fill_keys($key_array, 0);
foreach($array as &$a) {
  $a = rand();
}
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175