Skip to content

Instantly share code, notes, and snippets.

@jasonjohnson
Created March 4, 2012 04:10
Show Gist options
  • Save jasonjohnson/1970629 to your computer and use it in GitHub Desktop.
Save jasonjohnson/1970629 to your computer and use it in GitHub Desktop.
PHP Hash Implementation using DJB
<?php
class Hash {
var $buckets = array();
function put($key, $value) {
$this->buckets[$this->generate_hash($key)] = $value;
}
function get($key) {
return $this->buckets[$this->generate_hash($key)];
}
function generate_hash($str) {
$hash = 5381;
for($i = 0; $i < strlen($str); $i++) {
$hash = (($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;
@Follen
Copy link

Follen commented Mar 4, 2012

pretty helpful!~

@andrey-kabakchiev
Copy link

The djb hash algorithm depends on integer overflows and php has unpredictable behaviour about this (different version, architectures, etc.). This can lead to different results which of course is not something we want. :) You can read about it here: http://stackoverflow.com/questions/300840/force-php-integer-overflow

I've made some changes in this gist: https://gist.github.com/aralbald/5772554

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment