Søren Beck Jensen
Søren Beck Jensen

Reputation: 1676

In php how would I generate a fixed number from a string within a certain value range

Let's say I have a database of 100,000 more or less random strings and I want to generate a number from each string between 1 and 500.

My method should always generate the same number (given the same string) and it should be an even distribution of numbers from 1 to 500.

Any ideas?

Upvotes: 0

Views: 116

Answers (2)

dendini
dendini

Reputation: 3952

You could also use something like:

function string_to_decimal($hex_str)
{
    $arr = str_split($hex_str, 4);
    foreach ($arr as $grp) {
        $dec[] = str_pad(hexdec($grp), 5, '0', STR_PAD_LEFT);
    }
    return implode('', $dec);
}

Upvotes: 0

Salman Arshad
Salman Arshad

Reputation: 272086

Seems like you need a hashing function. You can use crc32 and modulus operator:

echo abs(crc32("hello world")) % 500 + 1;

Upvotes: 1

Related Questions