(PHP 8 >= 8.6.0)
Time\Duration::compare — Compares two durations
Compares the durations a and
b, taking their signs into account.
The return value is suitable as the result of a callback for
usort().
The same ordering is used by the comparison operators when both operands are Time\Duration objects.
aThe first duration.
bThe second duration.
Returns a value less than 0 if
a is shorter than b, a value
greater than 0 if a is longer
than b, and 0 if both durations
are equal.
No particular meaning can be reliably inferred from the value aside from
its sign.
Negative durations are always smaller than positive ones.
Example #1 Time\Duration::compare() example
<?php
$oneSecond = \Time\Duration::fromSeconds(1);
$oneAndAHalfSeconds = \Time\Duration::fromMilliseconds(1500);
$billionNanoseconds = \Time\Duration::fromNanoseconds(1_000_000_000);
var_dump(\Time\Duration::compare($oneSecond, $oneAndAHalfSeconds) < 0);
var_dump(\Time\Duration::compare($oneAndAHalfSeconds, $oneSecond) > 0);
var_dump(\Time\Duration::compare($oneSecond, $billionNanoseconds) === 0);
// Negative durations are smaller than positive ones.
var_dump(\Time\Duration::compare($oneSecond->negate(), $oneSecond) < 0);Il precedente esempio visualizzerà:
bool(true) bool(true) bool(true) bool(true)
Example #2 Sorting durations with Time\Duration::compare()
<?php
$durations = [
\Time\Duration::fromMinutes(2),
\Time\Duration::fromMilliseconds(250),
\Time\Duration::fromSeconds(5),
];
usort($durations, \Time\Duration::compare(...));
foreach ($durations as $duration) {
printf("%d.%09d\n", $duration->seconds, $duration->nanoseconds);
}Il precedente esempio visualizzerà:
0.250000000 5.000000000 120.000000000