For those who stayed floating, let’s go to a practical example in the real world
Imagine you built a system where you need to implement several levels of access.
Example, allow or deny a system area, allow or deny editing a text group, etc.
Normally we would do something exhausting and difficult to manage like this
tabela permissões:
usuario_id
editar
adicionar
deletar
desativar
ver
In an SQL query would look something like SELECT editar, adicionar, deletar FROM ...
It seems simple, but imagine when you need to add more permissions.
You will have to create new columns and add implementations in the system scripts.
Using bitwise operators, it could simplify so
tabela permissões:
usuario_id
bit_flag
So you ask, how do I know if this user can edit, add, etc?
With only 1 numerical column, you can identify several permissions.
Example, suppose the query SELECT bit_flag FROM ...
return the number 79.
With that, we have the following routine:
$rs = 79; // o que retornou do banco
function showPermission($rs, $b)
{
return 'Acesso '.$b.' '.(($rs & $b)? 'permitido' : 'negado');
}
echo showPermission($rs, 1).PHP_EOL.'<br />';
echo showPermission($rs, 2).PHP_EOL.'<br />';
echo showPermission($rs, 4).PHP_EOL.'<br />';
echo showPermission($rs, 8).PHP_EOL.'<br />';
echo showPermission($rs, 16).PHP_EOL.'<br />';
echo showPermission($rs, 32).PHP_EOL.'<br />';
echo showPermission($rs, 64).PHP_EOL.'<br />';
echo showPermission($rs, 128).PHP_EOL.'<br />';
Will return:
Acesso 1 permitido
Acesso 2 permitido
Acesso 4 permitido
Acesso 8 permitido
Acesso 16 negado
Acesso 32 negado
Acesso 64 permitido
Acesso 128 negado
Note that 79 is precisely the sum of 1, 2, 4, 8 and 64.
Change the number to 78 and you will see that permission 1 will change to "denied".
In the system you define how you want what each operand represents.
Example,
1 -> representa adicionar
2 -> representa editar
4 -> representa deletar
This is just a simple example of what you can do with bitwise operators. Not only in PHP but in other languages as well.
The same as in any other language. Know if a number is even, multiply/divide by 2 potentials faster, join flags, make bit maps to filter DB results, etc. Knowing how to use, there is a lot that is more practical and fast bit by bit. It is that usually who learns only PHP is very superficial, since the language is basically used for simple scripts (which are artificially complicated with academicism of other languages, in many cases).
– Bacco
@Bacco answers there with a few examples :D
– rray
@rray hope someone does it, I just put a comment to advance the subject. It would be nice an answer with small algorithms example. If I have some time later, I can try to do something. But I prefer the community to post examples, it’s cooler with several answers. If you (or someone) want to take some of the examples I said and use it in your own response, feel free.
– Bacco