Questions And Answers

More Tutorials

Using a bitmask in PHP

Example 1

const FLAG_1 = 0b0001; // 1
const FLAG_2 = 0b0010; // 2
const FLAG_3 = 0b0100; // 4
const FLAG_4 = 0b1000; // 8
// Can you see the pattern? ;-)

function show_flags ($flags) {
  if ($flags & FLAG_1) {
    echo "You passed flag 1!<br>\n";
  if ($flags & FLAG_2) {
    echo "You passed flag 2!<br>\n";
  if ($flags & FLAG_3) {
    echo "You passed flag 3!<br>\n";
  if ($flags & FLAG_4) {
    echo "You passed flag 4!<br>\n";

show_flags(FLAG_1 | FLAG_3);

The others have offered good suggestions, but these days it's much more common to pass in associative arrays instead of bitmasks. It's much more readable and allows you to pass in other variables other than just true/false values. Something like this:

myFunction(['includeHidden' => true, 'fileExts' => false, 'string' => 'Xyz']);

function myFunction($options) {
    // Set the default options
    $options += [
        'includeHidden' => false,
        'fileExts' => true,
        'string' => 'Abc',

    if ($options['includeHidden']) {


In this page (written and validated by ) you learned about . What's Next? If you are interested in completing PHP tutorial, we encourage you simply to start here: PHP Tutorial.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.