php microtime() format value

2019-07-16 13:11发布

问题:

PHP's microtime() returns something like this:

0.56876200 1385731177 //that's msec sec

That value I need it in this format:

1385731177056876200 //this is sec msec without space and dot

Currently I'm doing something this:

$microtime =  microtime();
$microtime_array = explode(" ", $microtime);
$value = $microtime_array[1] . str_replace(".", "", $microtime_array[0]);

Is there a one line code to achieve this?

回答1:

You can do the entire thing in one line using regex:

$value = preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', microtime());

Example:

<?php
    $microtime = microtime();
    var_dump( $microtime );
    var_dump( preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', $microtime) );
?>

Output:

string(21) "0.49323800 1385734417"  
string(19) "1385734417049323800"

DEMO



回答2:

Unfortunately, due to PHP's restriction for float presentation (till 14 digits for whole numeric), there's little sense in using microtime() with true as parameter.

So, you'll have to work with it as with string (via preg_replace(), for example) or adjust precision to use native function call:

var_dump(1234567.123456789);//float(1234567.1234568)
ini_set('precision', 16);
var_dump(1234567.123456789);//float(1234567.123456789)

-so, it will be like:

ini_set('precision', 20);
var_dump(str_replace('.', '', microtime(1)));//string(20) "13856484375004820824" 

-still not "one-liner", but you're aware of reason that causes such behavior so you can adjust precision only once and then use that.