Skip to content

Instantly share code, notes, and snippets.

@andrey-kabakchiev
Forked from jasonjohnson/hash.php
Last active December 18, 2015 10:59
Show Gist options
  • Save andrey-kabakchiev/5772554 to your computer and use it in GitHub Desktop.
Save andrey-kabakchiev/5772554 to your computer and use it in GitHub Desktop.
<?php
class Hash {
private $buckets = array();
function put($key, $value) {
$this->buckets[$this->generate_hash($key)] = $value;
}
function get($key) {
$hash = $this->generate_hash($key);
if (isset($this->buckets[$hash])) {
return $this->buckets[$hash];
}
return false;
}
function intval32($value) {
if ($value < -2147483648) {
return -(-($value) & 0xffffffff);
} else if ($value > 2147483647) {
return ($value & 0xffffffff);
}
return $value;
}
function generate_hash($str) {
$hash = 5381;
for ($i = 0; $i < strlen($str); $i++) {
$hash = $this->intval32(((($hash << 5) + $hash) + ord($str[$i])));
}
return $hash;
}
}
$h = new Hash();
$h->put("key1", "Hello World!");
$h->put("key2", "Goodbye World!");
echo $h->get("key1") . PHP_EOL;
echo $h->get("key2") . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment