Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash method on multiple values?

Tags:

php

sorting

hash

Occasionally, I find I need to sort some objects, grouping them by multiple values. I usually accomplish this by concatenating the values together, with an underscore or other delineator in between, and then use that as an array index.

// group all objects with a common parent_id, date, and type
foreach ($objects as $obj) {
    $hash = $obj->parent_id . '_' . $obj->date  . '_' . $obj->type;
    $sorted_objects[$hash][] = $obj;
}

...ick! There's got to be a better way than abusing PHP's loose typing and string concatenation. Is there any way to perform a hash on multiple values? It seems I should be able to just do something like this:

$hash = sha1_multiple($obj->parent-id, $obj->date, $obj->type);

Am I already using the best method, or is there a better way?

like image 789
keithjgrant Avatar asked Feb 25 '23 20:02

keithjgrant


1 Answers

Using PHP's serialization makes it a bit neater, but less efficient:

function sha1_multiple() {
    $args = func_get_args();
    return sha1(serialize($args));
}
like image 62
Long Ears Avatar answered Mar 08 '23 10:03

Long Ears