1

Let's say I have the following flags that can be attached to a customer:

1 Hot
2 Urgent
4 Sensitive
8 Confidential

In my table I would store an active customer as an int of 6.

I figured doing things this way would save me a reference table and make querys faster.

How do I get PHP to interpret a 6 and for example light up a customer and active icon?

3
  • 4
    Someone can really be active without being a customer? A prospect can be cancelled? A prospect can be a customer? I think you need to think harder about the flags and the states they represent. Commented Oct 12, 2015 at 14:34
  • php.net/manual/en/language.operators.bitwise.php Commented Oct 12, 2015 at 14:35
  • Those are just quick examples. I have renamed them for you. Non are exclusive now but I get what you are saying. Commented Oct 13, 2015 at 5:40

1 Answer 1

1

Bitwise operators will do the trick:

$flag = 6; // value from the database
$customer = 2; // constant value
$active = 4; // constant value

if ($flag & $customer)
{
    print 'I am a customer.';
}

if($flag & $active)
{
    print 'I am active.';
}

I agree with @GordonLinoff though. Really consider if this is what you want because it's not easy to change later, and it could allow unexpected scenarios.

Sign up to request clarification or add additional context in comments.

3 Comments

so problems arise when one can not be without another?
@imperium2335 yes, that's one example. Also consider the possibility that one classification is removed; or, a new one is added and should be a default all existing records. Also, in you original example, do prospects and customers really differ by only a flag? It's unlikely that your tables are normalized in that case. I'm not saying don't ever use bitwise flags, but just think carefully about whether it's appropriate.
No, that was a poor example, realistically there is a column for state, being prospect or customer. Those definitions are stored in a separate table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.