<?php
class
hashTable
{
private
$collection
;
private
$size
= 100;
public
function
__construct(
$size
=
''
)
{
$bucketsSize
=
is_int
(
$size
)?
$size
:
$this
->size;
$this
->collection =
new
SplFixedArray(
$bucketsSize
);
}
private
function
_hashAlgorithm(
$key
)
{
$length
=
strlen
(
$key
);
$hashValue
= 0;
for
(
$i
=0;
$i
<
$length
;
$i
++) {
$hashValue
+= ord(
$key
[
$i
]);
}
return
(
$hashValue
%(
$this
->size));
}
public
function
set(
$key
,
$val
)
{
$index
=
$this
->_hashAlgorithm(
$key
);
$this
->collection[
$index
] =
$val
;
}
public
function
get(
$key
)
{
$index
=
$this
->_hashAlgorithm(
$key
);
return
$this
->collection[
$index
];
}
public
function
del(
$key
)
{
$index
=
$this
->_hashAlgorithm(
$key
);
if
(isset(
$this
->collection[
$index
])) {
unset(
$this
->collection[
$index
]);
return
1;
}
else
{
return
0;
}
}
public
function
exist(
$key
)
{
$index
=
$this
->_hashAlgorithm(
$key
);
if
(
$this
->collection[
$index
]){
return
1;
}
else
{
return
0;
}
}
public
function
size()
{
$size
= 0;
$length
=
count
(
$this
->collection);
for
(
$i
=0;
$i
<
$length
;
$i
++) {
if
(
$this
->collection[
$i
]) {
$size
++;
}
}
return
$size
;
}
public
function
val()
{
$size
= 0;
$length
=
count
(
$this
->collection);
for
(
$i
=0;
$i
<
$length
;
$i
++) {
if
(
$this
->collection[
$i
]) {
echo
$this
->collection[
$i
].
"<br />"
;
}
}
}
public
function
sort(
$type
=1)
{
$length
=
count
(
$this
->collection);
$temp
=
array
();
for
(
$i
=0;
$i
<
$length
;
$i
++) {
if
(
$this
->collection[
$i
]) {
$temp
[] =
$this
->collection[
$i
];
}
}
switch
(
$type
) {
case
1:
sort(
$temp
, SORT_REGULAR);
break
;
case
2:
sort(
$temp
, SORT_NUMERIC);
break
;
case
3:
sort(
$temp
, SORT_STRING);
break
;
case
4:
sort(
$temp
, SORT_LOCALE_STRING);
break
;
}
echo
"<pre>"
;
print_r(
$temp
);
}
public
function
rev(
$type
=1)
{
$length
=
count
(
$this
->collection);
$temp
=
array
();
for
(
$i
=0;
$i
<
$length
;
$i
++) {
if
(
$this
->collection[
$i
]) {
$temp
[] =
$this
->collection[
$i
];
}
}
switch
(
$type
) {
case
1:
rsort(
$temp
, SORT_REGULAR);
break
;
case
2:
rsort(
$temp
, SORT_NUMERIC);
break
;
case
3:
rsort(
$temp
, SORT_STRING);
break
;
case
4:
rsort(
$temp
, SORT_LOCALE_STRING);
break
;
}
echo
"<pre>"
;
print_r(
$temp
);
}
}
$list
=
new
hashTable(200);
$list
->set(
"zero"
,
"zero compare"
);
$list
->set(
"one"
,
"first test"
);
$list
->set(
"two"
,
"second test"
);
$list
->set(
"three"
,
"three test"
);
$list
->set(
"four"
,
"fouth test"
);
echo
$list
->val();
echo
"after sorted : <br />"
;
$list
->rev(3);