Skip to content
Advertisement

Get bitwise and of all elements of an array in php

if i have and array like

$array=[11,11,13,18,19];

and i want to do a bitwise add operator for all elements like

echo $array[0]&$array[1]&$array[2];

What will be the logic and how to do it ?

Advertisement

Answer

This can be achieved with the following one-liner:

echo array_reduce($array, fn($carry, $item) => $carry & $item, reset($array));

It uses array_reduce to ‘loop’ over the array, reducing it to one value. The callback function performs the bitwise operation.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement