Just like this:
1 = 1
2 = 2
3 = 1,2
5 = 1,4
6 = 2,4
7 = 1,2,4
9 = 1,8
15 = 1,2,4,8
31 = 1,2,4,8,16
It seems need some binary function.
Found this!
function split($n) {
$n |= 0;
$pad = 0;
$arr = array();
while ($n) {
if ($n & 1) array_push($arr, 1 << $pad);
$pad++;
$n >>= 1;
}
return $arr;
}
You can use decbin to make the number binary, then use an array as the lookup to what number in binary it is.
I use array_intersect to find the "true" values and use array_intersect_key to match them in the $arr. This is a non looping solution that may or may not be faster.
$arr= [16,8,4,2,1];
$number = 13;
$bin = str_split(str_pad(decbin($number),count($arr),"0",STR_PAD_LEFT));
Echo implode(",", array_intersect_key($arr,array_intersect($bin, ["1"])));
If the order is important then you need to sort it prior to output.
$nums = array_intersect_key($arr,array_intersect($bin, ["1"]));
sort($nums);
Echo implode(",", $nums);