Php array bitwise

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

t

$foo = array(flag1, flag2);

at

$bar = flag1 | flag2;

Does PHP have any good features that will do this for me already well?

+5
source share
4 answers

array_reduce will reduce the array to one value for you:

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

The abbreviation is also sometimes called fold (collapse left or collapse right) in other languages.

+14
source

You can do it like this

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

If the size of your array is unknown, you can 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'));
+3
source
$values = array_reduce($foo,function($a,$b){return is_null($a) ? $b : $a | $b;});

PHP < 5.3 ( ), :

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

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

);

+1

: array_sum.

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

All Articles