jonjbar
jonjbar

Reputation: 4066

Generate a valid array key from an URL string in PHP

I have a PHP array with some predefined values:

$aArray = array(
    0 => 'value0',
    1 => 'value1'
);

I need to create a function where the string input will always return the same, valid, array key so that when I call:

GiveMeAKey('http://www.google.com');  // May return 0 or 1

I receive always the same key (I don't care which one) from the array. Obvisously I can't store the relationship in a database and the string passed to the GiveMeAKey method can be any URL.

I wonder if there is a way of doing that ?

Upvotes: 2

Views: 1129

Answers (3)

Artefacto
Artefacto

Reputation: 97835

You can generate something random from the input string and choose a key based on that:

function GiveMeAKey($str, array $array) {
    return $array[crc32($str) % count($array)];
}

Example:

echo GiveMeAKey("http://www.google.com/", $aArray);    //value0
echo GiveMeAKey("http://www.altavista.com/", $aArray); //value1

NOTE: CRC32 is not a good hash function, but has the nice property it returns a 32-bit number you can use with the % operator. But for your purposes, it suffices.

Upvotes: 3

Ghpst
Ghpst

Reputation: 309

Another alternative to a hash function, could be something like calculating the ASCII sum of the string and then return it in modulo 2.

Upvotes: 1

poke
poke

Reputation: 388023

I think what you want is a Hash function.

Upvotes: 1

Related Questions