Reputation: 2473
Trying to populate a previously created associative array, with values where values are randomly created. I cannot spot what I am doing wrong.
<?php
$value_min = 1;
$value_max = 3;
$my_array = array (
"dice_1" => null,
"dice_2" => null,
"dice_3" => null
);
foreach(range($value_min, $value_max) as $key => $value) {
$my_array[] = random_int($value_min, $value_max);
};
print_r($my_array);
Outcome:
Array
(
[dice_1] =>
[dice_2] =>
[dice_3] =>
[0] => 2
[1] => 2
[2] => 3
)
Expected outcome
(
[dice_1] => 2
[dice_2] => 2
[dice_3] => 3
)
Note: value can of course diff since they are created with random numbers
Upvotes: 0
Views: 67
Reputation: 18557
Here you can do something like this,
$t = range($value_min, $value_max);
shuffle($t);
$temp = array_combine(array_keys($my_array), $t);
I am fetching keys of $my_array
and shuffled range array.
Then combining them as keys as first argument and shuffled range array as second argument.
Demo.
EDIT
In that case you can traverse my_array,
foreach($my_array as $key => &$value) { // & to save data directly to its address
$value = random_int($value_min, $value_max);
};
Demo.
Upvotes: 1
Reputation: 1712
$value_min = 1;
$value_max = 3;
$my_array = array (
"dice_1" => null,
"dice_2" => null,
"dice_3" => null
);
$i=1;
foreach(range($value_min, $value_max) as $key => $value) {
$my_array["dice_".$i] = random_int($value_min, $value_max);
$i++;
};
print_r($my_array);
Upvotes: 0
Reputation: 455
just change the foreach
foreach($my_array as $key => $value) {
$my_array[$key] = random_int($value_min, $value_max);
};
Upvotes: 1