views:

28

answers:

1

I'm attempting to create a function with flags as its arguments but the output is always different with what's expected :

define("FLAG_A", 1);  
define("FLAG_B", 4);  
define("FLAG_C", 7);  
function test_flags($flags) {  
 if($flags & FLAG_A) echo "A";  
 if($flags & FLAG_B) echo "B";  
 if($flags & FLAG_C) echo "C";   
}  
test_flags(FLAG_B | FLAG_C); # Output is always ABC, not BC  

How can I fix this problem?

+3  A: 

Flags must be powers of 2 in order to bitwise-or together properly.

define("FLAG_A", 1);  
define("FLAG_B", 2);  
define("FLAG_C", 4);  
function test_flags($flags) {  
 if($flags & FLAG_A) echo "A";  
 if($flags & FLAG_B) echo "B";  
 if($flags & FLAG_C) echo "C";   
}  
test_flags(FLAG_B | FLAG_C); # Output is always ABC, not BC  
Ignacio Vazquez-Abrams
Aah, thanks so much for your help!