Subversion Repositories php_utils

Rev

Rev 28 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
27 daniel-mar 1
<?php
2
 
3
/*
4
 * fixed_length_microtime() for PHP
5
 * Copyright 2022 Daniel Marschall, ViaThinkSoft
29 daniel-mar 6
 * Version 2022-03-08
27 daniel-mar 7
 *
8
 * Licensed under the Apache License, Version 2.0 (the "License");
9
 * you may not use this file except in compliance with the License.
10
 * You may obtain a copy of the License at
11
 *
12
 *     http://www.apache.org/licenses/LICENSE-2.0
13
 *
14
 * Unless required by applicable law or agreed to in writing, software
15
 * distributed under the License is distributed on an "AS IS" BASIS,
16
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17
 * See the License for the specific language governing permissions and
18
 * limitations under the License.
19
 */
20
 
29 daniel-mar 21
function fixed_length_microtime($unique=true) {
27 daniel-mar 22
        // This function outputs a fixed-length microtime (can be used for sorting)
29 daniel-mar 23
        // Optionally, it ensures that the output is always different by waiting 1 microsecond
27 daniel-mar 24
 
28 daniel-mar 25
        $ary = explode('.', (string)microtime(true));
27 daniel-mar 26
        if (!isset($ary[1])) $ary[1] = 0;
28 daniel-mar 27
        $ret = $ary[0].'_'.str_pad($ary[1], 4, '0', STR_PAD_RIGHT);
27 daniel-mar 28
 
29 daniel-mar 29
        if ($unique) {
30
                // Make sure value changes by waiting 1 microsecond.
31
                usleep(1);
27 daniel-mar 32
        }
33
 
34
        return $ret;
35
}