You can use bitwise operations. Essentially, you achieve the effect by doing a bitwise OR on two or more numbers, and then checking if a number was OR'ed in by doing a bitwise AND on the number that you want to test for.
Example:
You want the user to select which languages they are fluent in. The options you present them are English, German, Russian, and Spanish.
First, start by defining the options in powers of 2:
$LANGUAGE_ENGLISH = 2;
$LANGUAGE_RUSSIAN = 4;
$LANGUAGE_GERMAN = 8;
$LANGUAGE_SPANISH = 16;
Let's say the user selects English and Russian. You would combine the options as follows:
$selected_options = 0; // we'll store the result in here
$selected_options = $LANGUAGE_ENGLISH | $LANGUAGE_RUSSIAN;
//It can also be express as:
//$selected_options |= $LANGUAGE_ENGLISH;
//$selected_options |= $LANGUAGE_RUSSIAN;
The $selected_options
variable now contains our user's options. To check if an option was stored, you do a bitwise AND. If the result is 0, then the value was not stored. Otherwise, the value was stored.
Example:
if ($selected_options & $LANGUAGE_ENGLISH != 0)
echo "English was selected";
else
echo "English was NOT selected";
Requirements:
All numbers need to have non-overlapping bits. The easiest way to prevent overlaps is by only using numbers in powers of 2. For example, in the below table, 3
overlaps with 2
, and cannot be used with 2
. 1
, however, does not overlap with 2
or 4
, and can therefore be used with both.
1: 0001
2: 0010
3: 0011
4: 0100
Hope that helps