Skip to content
Advertisement

Use a String as a Seed for a Randomiser

It is possible to use a string as a randomiser seed to generate a number between two values in PHP.

For example:

$seed = 'John';

srand($seed);

echo rand(1, 10);

Advertisement

Answer

You can calculate the hash of the input string to get an integer (with crc32() in example) and then, use that number as seed :

<?php
$StringSeed = "John";
$IntSeed = crc32($StringSeed);

echo "Hash Value : $IntSeed" . PHP_EOL;

srand($IntSeed);

echo rand(1, 10); // 8
echo rand(1, 10); // 4
echo rand(1, 10); // 10

Try it yourself

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement