3

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?

Matías Cánepa
  • 5,201
  • 4
  • 49
  • 88

2 Answers2

6

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

Ben Fortune
  • 28,143
  • 10
  • 73
  • 75
h2ooooooo
  • 36,580
  • 8
  • 61
  • 97
  • `$value = preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', microtime(true));` will not work as expected. And why using a regular expression where a simple calculation is enough? – l-x Nov 29 '13 at 14:18
  • @l-x It **does** work as expected though - check the demo. OP wanted it in a single line - you can't do that without regex. "*Is there a one line code to achieve this?*". – h2ooooooo Nov 29 '13 at 14:20
  • @l-x It will without `true`. Plus your answer isn't in the format that OP wanted. – Ben Fortune Nov 29 '13 at 14:20
  • @h2ooooooo that's what I'm talking about! =) thank you very much – Matías Cánepa Nov 29 '13 at 14:35
3

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.

Alma Do
  • 35,363
  • 9
  • 65
  • 99