For those who have floated, let's take a practical example in the real world
Imagine that you have built a system where you need to implement multiple levels of access.
Example, allow or deny a system area, allow or deny editing of a text group, etc.
Normally we would do something exhaustive and difficult to manage like this
tabela permissões:
usuario_id
editar
adicionar
deletar
desativar
ver
In an SQL query it would look something like SELECT editar, adicionar, deletar FROM ...
It seems simple, though, imagine when you need to add more permissions.
You will need to create new columns and add implementations to system scripts.
Using bitwise operators, you could simplify this way
tabela permissões:
usuario_id
bit_flag
So you ask, how will I know if this user can edit, add, etc?
With only 1 numeric column, you can identify various permissions.
Example, suppose the query SELECT bit_flag FROM ...
returns the number 79.
With this, 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 just the sum of 1, 2, 4, 8, and 64.
Modify the number to 78 and you will see that permission 1 will change to "denied."
In the system you define as 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.