1. static inline ulong zend_inline_hash_func(char *arKey, uint nKeyLength)
2. {
3. register ulong hash = 5381;
4.
5. /* variant with the hash unrolled eight times */
6. for (; nKeyLength >= 8; nKeyLength -= 8) {
7. hash = ((hash << 5) + hash) + *arKey++;
8. hash = ((hash << 5) + hash) + *arKey++;
9. hash = ((hash << 5) + hash) + *arKey++;
10. hash = ((hash << 5) + hash) + *arKey++;
11. hash = ((hash << 5) + hash) + *arKey++;
12. hash = ((hash << 5) + hash) + *arKey++;
13. hash = ((hash << 5) + hash) + *arKey++;
14. hash = ((hash << 5) + hash) + *arKey++;
15. }
16. switch (nKeyLength) {
17. case 7: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
18. case 6: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
19. case 5: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
20. case 4: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
21. case 3: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
22. case 2: hash = ((hash << 5) + hash) + *arKey++; /* fallthrough... */
23. case 1: hash = ((hash << 5) + hash) + *arKey++; break;
24. case 0: break;
25. EMPTY_SWITCH_DEFAULT_CASE()
26. }
27. return hash;
28. }
Asked
Active
Viewed 535 times
2

DaveRandom
- 87,921
- 11
- 154
- 174

ajx
- 117
- 1
- 4
2 Answers
4
All the hash tables use that hashing algorithm; hash tables in PHP are used, for instance, to implement arrays and symbol tables, among many other things.
The algorithm, as pointed in the header is DJBX33A (Daniel J. Bernstein, Times 33 with Addition).

Artefacto
- 96,375
- 17
- 202
- 225
-
So it's only used internally by PHP,without such an api for PHP users? – ajx Nov 19 '10 at 08:03
-
1I was going to answer with this too, but wasn't sure and got lost looking for sources. Looks like you confirmed it, +1 – BoltClock Nov 19 '10 at 08:03
-
@ajx As far as I know there's no API for user-land. – Artefacto Nov 19 '10 at 10:24
-
@ajx It's easily implemented in PHP: $key = "string to hash"; $hash = 5381; for ($len = strlen($key), $i = 0; $i < $len; $i++) { $hash = $hash * 33 + ord($key[$i]); } – nikita2206 Mar 24 '13 at 12:33
-
@Artefacto, Why is this algorithm chosen instead of the one Java uses `s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]`? – Pacerier Aug 10 '13 at 04:28
1
You can use this link to see where this function is used: http://lxr.php.net/search?q=+zend_inline_hash_func&defs=&refs=&path=&hist=&project=PHP_5_4
looks like there are 3 php extensions (including standard) where this function is used.

an_animal
- 86
- 6