Gandalf
Gandalf

Reputation: 13693

Php weak random value generator for cases where repeated values are useful

I am generating test data for use in my frontend and I want to generate ages. Currently I am generating age between 18 and 100 using rand(1,100) like this:

require_once 'vendor/autoload.php';
$faker = Faker\Factory::create();

$superstars = array("Adam Cole","Finn Balor","Pete Dunne","Jordan Devlin","Noam Dar");
$fan_favourite_superstar_name = $superstars[ mt_rand( 0, count($superstars) -1 ) ];

$cities = array("London","Manchester","Leeds","Bristol");
$fan_location = $cities[ mt_rand( 0, count($cities) -1 ) ];

$the_models = array("Iphone","Nokia","Huawei","Samsung");
$fan_phone_model = $the_models[ mt_rand( 0, count($the_models) -1 ) ];


$array = Array (
    "0" => Array (
        "id" => uniqid(),
        "fan_favourite_superstar_name" => $fan_favourite_superstar_name,
        "fan_location" => $fan_location,
        "fan_phone_model" => $fan_phone_model,
        "fan_name" => $faker->name,
        "fan_age" => rand(18,100),
        "fan_comments" => $faker->text,
        "fan_picture" => rand(1,500),
        "last_updated" => time() + rand(1,1000),
    ),

However, I would like my ages to repeat although not completely. Is there a weak randomness generator apart from rand that can ensure that the an ages generated randomly repeat themselves n times?.

Upvotes: 0

Views: 34

Answers (1)

Banzay
Banzay

Reputation: 9470

Here is a function just to show my suggestion of solution:

function getAge($start = 18, $end = 100, $repeat = 20){
    $result = null;
    static $ages = array();
    if ( empty($ages) ) {
        for ($i= $start; $i <= $end; $i++) {
            for($j = 0; $j < $repeat; $j++)
            $ages[] = $i;
        }
    }
    $index = rand(0, count($ages));
    $result = $ages[ $index ];
    unset($ages[ $index ]);
    $ages = array_values($ages);

    return $result;
}

Upvotes: 1

Related Questions