3v4l.org

run code in 300+ PHP versions simultaneously
<?php function isLongerThanCT(string $input, int $targetLength): bool { $amount = PHP_INT_SIZE === 8 ? 63 : 31; $len = strlen($input); // use mb_strlen($input, '8bit'); on older PHP $res = (($targetLength - $len) >> $amount) & 1; /* * It's worth taking a moment to explain what the hell the line above is doing. * * ($targetLength - $len) will return a negative value if $targetLength is larger than $len. * * By two's complement, negative values when shifted 31 or 63 places to the right will have a lower * bit set. We then use a bit mask of `1` and the bitwise `&` operator on the result of the bitshift. * * End result? It's the same as if we did the following, except constant-time: * $res = (int) ($len > $targetLength); */ return (bool) ($res); } $long = str_repeat('A', 72); var_dump( isLongerThanCT($long, 71), isLongerThanCT($long, 72), isLongerThanCT($long, 73) );
Output for 8.2.0 - 8.2.27, 8.3.0 - 8.3.15, 8.4.1 - 8.4.2
bool(true) bool(false) bool(false)

preferences:
46.78 ms | 406 KiB | 5 Q