/**
* Rounds an integer down to the previous power of 2.
*
* return int The previous power of 2 less than or equal to $n
*/
function roundToPreviousPowerOf2(int $n): int {
if ($n <= 0) {
return 0;
}
return (int) pow(2, floor(log($n, 2)));
}
$num = 21;
echo "Previous power of 2: " . roundToPreviousPowerOf2($num) . PHP_EOL;
/*
run:
Previous power of 2: 16
*/