2

I have an array that I want to use with the the bitwise inclusive or operation.

The two solutions at the moment are:

A foreach() loop that evaluates them in order

$final = 0;
foreach($bits as $bit)
  $final = $final | $bit;
}

Imploding the array with the bitwise OR as the glue, and eval() the string

eval(implode(' | ', $bits));

Are these the only options or am I missing a simple native array method?

6
  • Check if there is atleast one 1 in the array. If there is, then the output is 1, else 0 :P Commented Jan 4, 2014 at 23:25
  • 3
    If the $bits are already exclusive, then array_sum would do. Commented Jan 4, 2014 at 23:27
  • @HamZa, sorry, to clarify this is used before a following & check against another value, so I need more than a boolean response. Thanks Commented Jan 5, 2014 at 0:29
  • @mario Of course, thank you. array_sum with array_unique does it! Commented Jan 5, 2014 at 0:31
  • 1
    @HamZa the resulting value is required for another bitwise operation afterwards, so I required a combination of the array's bits Commented Jan 5, 2014 at 0:33

1 Answer 1

2

Following @mario's comment, the solution is:

array_sum(array_unique($bits));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.