26
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

PHP UUID version4 を生成する

環境

PHP 7.3.1

コード

uuid_v4_factory.php

<?php declare(strict_types=1);

/**
 * UUID version 4
 */
class UuidV4Factory
{
    const PATTERN = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';

    /**
     * UUID 生成
     * @return string
     * @throws \Exception
     */
    public static function generate(): string
    {
        $chars = str_split(self::PATTERN);

        foreach ($chars as $i => $char) {
            if ($char === 'x') {
                $chars[$i] = dechex(random_int(0, 15));
            } elseif ($char === 'y') {
                $chars[$i] = dechex(random_int(8, 11));
            }
        }

        return implode('', $chars);
    }
}

使い方

$ php -a
php > require('uuid_v4_factory.php');
php > echo UuidV4Factory::generate();
3c68e561-2281-40a1-bcf6-91fe971b00e8
php > echo UuidV4Factory::generate();
de527f63-8f60-4034-aa21-bc091db13d6d
php > echo UuidV4Factory::generate();
4d052519-cc4f-4a51-9910-ed3c2842e457
php > echo UuidV4Factory::generate();
b796ef1a-1bb9-4d37-97d4-45f2f6da742f

500万回のUUID衝突テスト

<?php declare(strict_types=1);

ini_set('memory_limit', '-1');

require('./uuid_v4_factory.php');

$baseMemoryUsage = memory_get_usage();
$baseTime = microtime(true);

$data = [];
for ($i = 0; $i < 5000000; $i++) {
    $uuid = UuidV4Factory::generate();
    if (isset($data[$uuid])) {
        echo 'UuidDuplicateError' . PHP_EOL;
    }
    $data[$uuid] = true;
}

$maxMemoryUsage = (memory_get_peak_usage() - $baseMemoryUsage) / (1024 * 1024);
$processTime = microtime(true) - $baseTime;

echo sprintf('Max Memory Usage: %.3f [MB]', $maxMemoryUsage) . PHP_EOL;
echo sprintf('Process Time: %.2f [s]', $processTime) . PHP_EOL;
$ php uuid_v4_factory_test.php
Max Memory Usage: 736.000 [MB]
Process Time: 187.68 [s]

500万回を3回実行してみましたが、衝突はしませんでした。

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
26
Help us understand the problem. What are the problem?