Menu

Reference / Manticore\Ds

BitArray

finalclass
final class BitArray extends TypedArray

One bit per element: an array of booleans packed eight to a byte.

Assigning stores the truthiness of the value: bool as is, an int or float is true unless zero, a string is true unless '' or '0'. null, arrays and objects throw TypeError. Reading gives a bool. sum() counts the set bits and indexOf(true) finds the first one.

Example

use Manticore\Ds\BitArray;

$seen = new BitArray(10);       // ten bits, all false
$seen[3] = true;
$seen[7] = 1;                   // truthiness is stored
$seen[8] = '0';                 // '0' is false

var_dump($seen[3], $seen[8]);
echo $seen->sum(), "\n";        // set bits
echo $seen->indexOf(true), "\n";
echo $seen->indexOf(true, 4), "\n";

$seen->fill(false);
echo $seen->sum(), "\n";

Output

bool(true)
bool(false)
2
3
7
0

Methods

offsetGet()Returns the bit at $offset: $a[$offset].
sum()The number of set bits.

offsetGet()#source

function offsetGet(mixed $offset): bool

Returns the bit at $offset: $a[$offset].

Parameters

$offset mixed
the index

Returns

bool โ€” true when the bit is set

Throws

\OutOfBoundsException
when the position is outside 0..count-1
\TypeError
when $offset is of the wrong kind

sum()#source

function sum(): int

The number of set bits.

Returns

int โ€” the count of true elements

View source