Work with bit code

This is a bit of OT for SO, because I'm not trying to solve a specific problem, but just to understand how something can be implemented. But I'm after the code, so let's see how this happens ...

Let's say we had a flag for each day of the week, and we decided to save any combination of these flags as one number, for example:

0 = no days 1 = Monday 2 = Tuesday 4 = Wednesday 8 = Thursday 16 = Friday 32 = Saturday 64 = Sunday 127 = everyday 

How can this logic be implemented in PHP so that if I said β€œ13”, PHP would know that it would only check the boxes on Monday, Wednesday, and Thursday?

+7
php bitset
source share
2 answers

Bitwise AND s:

 $input = 13; if( $input & 1 ) { echo 'Monday'; } if( $input & 2 ) { echo 'Tuesday'; } if( $input & 4 ) { echo 'Wednesday'; } // etc 

change

You can avoid if with something like:

 $input = 13; $days = array('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'); for( $i=0; $i<7; $i++ ) { $daybit = pow(2,$i); if( $input & $daybit ) { echo $days[$i] . ' '; } } //output: mon wed thu 

There are more than these two ways to trick this particular cat, but the β€œbest” way depends on what your result / result should be.

+15
source share

To avoid duplicating the code structure (many similar if clauses) and introducing additional β€œmagic” numbers ( 2 , 7 ), as shown by Sammitch’s working sentences , I would prefer the following.

 $daymap = array( 1 => Monday, 2 => Tuesday, 4 => Wednesday, 8 => Thursday, 16 => Friday, 32 => Saturday, 64 => Sunday ); $input = 13; foreach ($daymap as $code => $name) { if ($input & $code) { echo $name.' '; } } 
+5
source share

All Articles