Subsecond times
While a Unix timestamp represents a date and time accurate to the second, many applications require times to be represented to the subsecond. PHP provides the function:
string microtime( )
This returns a string that contains both a Unix timestamp in seconds and a microsecond component. The returned string begins with the microsecond component, followed by the integer timestamp:
// prints the time now in the format "usec sec" // e.g., 0.34783800 1008553410 echo microtime( );
One common use of the function microtime( ) is to generate the seed for a random-number generator:
// Generate a seed. $seed = (float)microtime( ) * 100000000; srand($seed);
Because the microsecond component appears at the start of the string returned from microtime( ), the returned value can be converted to a float with the (float) cast operator. Multiplying the float result by 100,000,000 ensures that you pass a suitably varying integer to the seeding function srand( ). Random-number generation is covered in more detail in Section 2.9.