Sort foreach in php

2

I made a page that shows the hash in several hash_algos in order to study their differences, however I would like to sort by the size of the hash and not by the name of the hash_algos, the code is this,

<?php foreach (hash_algos() as $hash_algos) {
        $hash = hash($hash_algos, "salt", false); ?>
        <li>
            <span><?php echo $hash_algos; ?></span>
            <span><?php echo strlen($hash); ?></span>
            <span><?php echo $hash; ?></span>
        </li>
<?php } ?>

would like to be printed, be ordered by the size of the hash that in the case depending on the algos it will take from 8 to 128 and make a sub sort with the algos, ie put all of 8 with all fnv, the second sort is not so important, I just wanted to see how to sort the size.

example in ideone

Thank you in advance

    
asked by anonymous 12.10.2017 / 18:12

2 answers

3

It would be the case to first collect the data, and sort by displaying:

   // Primeiro coletamos os resultados em $results

   foreach (hash_algos() as $hash_algos) {
      $hash = hash($hash_algos, "salt", false);
      $results[] = ['algo' => $hash_algos, 'len' => strlen($hash), 'hash' => $hash];
   }

   // Em seguida usamos usort($array, 'funcao') para ordenar com uma função própria

   function compara($a, $b) {
      return $a['len'] - $b['len'];
   }
   usort($results, 'compara');

   // finalmente exibimos o resultado final, já ordenado

   foreach ($results as $result) {
      echo $result['algo'].' '.$result['len'].' '.$result['hash'].PHP_EOL;
   }

See working at IDEONE .


Better understand usort() in PHP manual:

  

link

    
12.10.2017 / 18:42
1

You can also use arsort :

$algos = array_flip(hash_algos());

foreach($algos as $algo => $len){
      $algos[$algo] = strlen(hash($algo, '', true));
}

arsort($algos);

foreach($algos as $algo => $len){
    echo $algo . ' => ' .$len;
    echo '<br>';
}

Remembering that using false in the last parameter of hash , as used in your question, will return the size of the hash in HEX. The hexadecimal is twice the original length.

A SHA-512 has exact 512 bits, but hexadecimal-encoded will use 1024 bits to store 512 bits. Already using Base64 the same 512 bits would pass to 704 bits, for comparison. So I believe what you want is the original length and not hexadecimal, so why not hexadecimal .

    
13.10.2017 / 15:54