0

I have a roles table on my database that was set in a binary sequence:

1-Admin
2-Teacher
4-Student
8-Principal
16-Parent
32-Guest
more..
more..

There are times an admin can be a teacher so his role will be 3 (1+2), as well as a principal can also be a teacher with the role:10 (8+2). This way I can setup variety of roles such as Guest+Parent=48. Hope you get the idea. Now, adding roles in PHP and inserting them into the database is easy. Now, my question is: how do I extract roles individually from the whole number. For example, if a person's role is 44, how can I get in PHP that this person is a (Guest), (Principal), and (Student). (Please disregard the logic of a student can not be a parent for this question.) Is there a PHP function for this?

nice_dev
  • 17,053
  • 2
  • 21
  • 35
  • 2
    You can just use logical AND. `3 & 1 = true`, so a teacher is admin. Detailed example for Javascript: https://stackoverflow.com/questions/66941063/bitwise-operation-with-0x88 – Markus Zeller Jun 16 '22 at 11:21
  • Does this answer your question? [Most efficient way to extract bit flags](https://stackoverflow.com/questions/2791869/most-efficient-way-to-extract-bit-flags) – CBroe Jun 16 '22 at 11:23
  • Thank you for the 3 & 1 = true example. Can you please help me how to write this in PHP? – Heather Blue Jun 16 '22 at 11:28
  • 1
    Don't do it this way for roles management. It isn't scalable and makes it hard to read. Imagine a company with 1000s of roles or responsibilities. You will run out of bit positions. – nice_dev Jun 16 '22 at 11:34
  • @HeatherBlue In PHP it would be `3 & 1` – Justinas Jun 16 '22 at 11:34
  • 1
    I understand and agree but this was already done. I am just adding features. – Heather Blue Jun 16 '22 at 11:36

0 Answers0