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) );

preferences:
24.35 ms | 405 KiB | 5 Q