views:

35

answers:

1

How can I parse a configuration value with PHP which is a number and a total of other numbers.

One example of this is:

1 -> Logging Enabled
2 -> Error Reporting Enabled
4 -> E-Mail Reporting Enabled

3 -> Logging + Error Enabled
5 -> Logging + E-Mail Enabled

+3  A: 

You don't just have a sum -- you have yourself a set of flags, or a bit field, with each flag represented by one bit.

$logging     = !!($cfgval & 1);
$errorReport = !!($cfgval & 2);
$emailReport = !!($cfgval & 4);

The "!!" just ensures that numbers that aren't 0 (ie: numbers with the specific bit set) end up as the same "true" value that the rest of PHP uses, so stuff like ($logging == true) always works as expected. It's not required, but i highly recommend you convert the value to a boolean somehow; (bool) would work as well, even if it is 3 times as many characters. :)

As long as you keep the numbers as powers of two (1, 2, 4, 8, 16, 32...), it's easy to extend this up to 31-32 different flags (integers are 32 bits in size, but the top bit is a sign bit which acts kinda funny if you don't know about "two's complement" math).

cHao
@chao, do u think, that one will put a configuration key/value like 1024, 2048, ..., 16384, ... so on? is it handy or feasible? i dont think so.
Sadat
@Sadat: sure. Define constants for the values, and it's extremely easy to work with. Not so easy for a human to put into a config file, but that's something a decent setup/install page could whip up in no time. Or you could use hex numbers, where 4 bits == 1 digit, and it gets a lot easier even for humans.
cHao
Why should `!!` be better than `(bool)`?
Mikulas Dite
It'd work the same, i imagine. `!!` is shorter, though, and makes just as much sense to me.
cHao