veilig
veilig

Reputation: 5135

Combine flags in array to single value using bitwise OR

If I have an array of flags and I want to combine them with a bitwise conjunction

ie:

$foo = array(flag1, flag2);

into

$bar = flag1 | flag2;

Does PHP have any good functions that will do this nicely for me already?

Upvotes: 7

Views: 3267

Answers (4)

Bell
Bell

Reputation: 455

A simple suggestion to the accepted answer: create a sibling to array_sum.

function array_or (array $array): int {
    return array_reduce($array, function($a, $b) { return $a | $b; }, 0);
  }

Upvotes: 0

Wrikken
Wrikken

Reputation: 70500

$values = array_reduce($foo,function($a,$b){return is_null($a) ? $b : $a | $b;});

PHP < 5.3 (no closures), either of these two:

function _mybitor($a,$b){return is_null($a) ? $b : $a | $b;}
$values = array_reduce($foo,'_mybitor');

or

$values = array_reduce($foo,create_function('$a,$b','return is_null($a) ? $b : $a | $b;'));

);

Upvotes: 1

Benjamin Cremer
Benjamin Cremer

Reputation: 4822

You could do it like so

$bar = $foo[0] | $foo[1]

If the size of your array is unknown you could use array_reduce like this

// in php > 5.3
$values = array_reduce($flagArray, function($a, $b) { return $a | $b; });
// in php <= 5.2
$values = array_reduce($flagArray, create_function('$a, $b', 'return $a | $b'));

Upvotes: 3

Daniel Egeberg
Daniel Egeberg

Reputation: 8382

The array_reduce will reduce an array to a single value for you:

$res = array_reduce($array, function($a, $b) { return $a | $b; }, 0);

Reduce is also sometimes called fold (fold left or fold right) in other languages.

Upvotes: 19

Related Questions