Here is a function without any loops (mainly for the pleasure of it :)):
function getTypes($int) { $types = array('Type A','Type B','Type C','Type D','Type E');//defining types $t = array_reverse(str_split(decbin($int)));//converting $int to an array of bits $types = array_slice($types,0,ceil(log($int,2)));//slicing the array to the same size as number of bits in the $int $t = array_combine($types,$t);// Creating a new array where types are keys and bits are values return array_keys($t,1);// returning an array of keys which have a value of 1 }
However, this does not mean that it is effective. If you use a bitmask, you are better off checking the values ββusing bitwise operators such as bitwise and (&). For example, if you want to check if your integer contains Type D and Type E, you should do
if ($integer & 8 & 16)
To check each individual type, I would request a loop with a bit-break operator
function getTypes($int) { $result = array(); $types = array('Type A','Type B','Type C','Type D','Type E'); foreach($types as $type) { if ($int & 1)//checking if last bit is 1 (exactly the same as if($int%2) ) $result[]=$type; $int>>=1;//shifting integer bits to the right (exactly the same as $int = $int / 2) } return $result; }
source share