Return to Snippet

Revision: 10484
at January 1, 2009 13:35 by Jdub7


Initial Code
<?php
function isPermitted(Array $types, $userPermission) {
	$resourcePermission = array_reduce($types,create_function('$n,$m','$n += (int)$m; return $n;'), 0);
	return ($resourcePermission & (int)$userPermission)?true:false;
}
?>

Initial URL
http://www.litfuel.net/tutorials/bitwise.htm

Initial Description
Usage:

    define('PIRATE',bindec('0001')); // 1
    define('NINJA',bindec('0010')); // 2
    define('JEDI',bindec('0100')); // 4
    define('ADMIN',bindec('1000')); // 8
    
    $rpermit = array(PIRATE,JEDI); // Equivilent Flags '0101'
    
    $jim['permission'] = ADMIN + JEDI; // 12
    $joe['permission'] = ADMIN + NINJA; // 10
    $jon['permission'] = PIRATE; // 1
    
    var_dump(isPermitted($rpermit,$jim['permission']));
    var_dump(isPermitted($rpermit,$joe['permission']));

Initial Title
PHP bitwise permission

Initial Tags
php, array

Initial Language
PHP