microtime() or hrtime() for generating a unique number in a foreach loop

212 Views Asked by At

This has been asked before I think, but with key differences in the details...

So I want to group an array of product sub-arrays by a specific grouping value found in some sub-arrays. The grouping value, however, isn't set for all of them, only for those that are grouped together... This may sound a bit confusing so far, but I promise it'll get clearer when you take a look at the code below... So I'm doing this:

            $grouped = array();
            $i = 0;

            foreach ($items as $k => $item) {
                if ($items[$k]['ITEM.GRPCODE']) {
                    $groups[] = $items[$k]['ITEM.GRPCODE'];
                } else {
                    $i++;
                }

                $group = $item['ITEM.GRPCODE'] ? $item['ITEM.GRPCODE'] : md5(microtime());

                $grouped[$group][] = $item;
            }

            echo 'Groups: ' . count(array_unique($groups)) . ' - Single: ' . $i . '<br />';
            echo count($grouped) . '<br /><pre>' . print_r($grouped, true) . '</pre>';

At this point I should mention that I already know, for the current dataset, how many are the ones that are grouped together and how many are the single ones (the code I used to calculate each kind is also found in the code above)... So for an unchanged number of Groups/Single of 314/238 (the first echo), after a number of page refreshes I noticed that count($grouped) (the second echo) fluctuated from 552 (the sum of the two numbers above) to other values less than that, like 545, 547, 551, making it obvious that $group, when calculated by md5(microtime()) had produced 2-3 identical values, thus grouping products together that shouldn't be grouped together otherwise... Maybe the loop was so instant that even microtime() couldn't handle it? Then after some research I replaced md5(microtime()) with md5(hrtime(true)) and this time after A LOT of page refreshes I kept getting 314/238 for the first echo and 552 for the second one, which means that I was getting the expected groups every time...

So what's happening here? Is it that the loop was so instant that microtime() couldn't handle it? Is it that hrtime() is so more precise than microtime()? Is it something else?

Can you please share your thought and shed some light on this? Additionally, if neither md5(microtime()) nor md5(hrtime(true)) is the proper way to produce unique numbers in a foreach loop, could you give me another idea on how to do it better? Thanks in advance.

0

There are 0 best solutions below