john mossel
john mossel

Reputation: 2156

Splitting an array equally:

I have the following array:

$array = array(1,0,0,0,1,1,1,1,0,1,1,1,1,0,1,1,0,1,0,0,1,0,1);

I want split it up into individual arrays so that each array contains seven or less values.

So for example the first array will become:

$one = array(1,0,0,0,1,1,1)
$two = array(1,0,1,1,1,1,0)
$three = array(1,1,0,1,0,0,1);
$four = array(0,1);

Also how would you count the number of times 1 occurs in array one?

Upvotes: 0

Views: 99

Answers (3)

Rob Raisch
Rob Raisch

Reputation: 17367

Assuming you want to preserve the contents of the array, I'd use array_slice() to extract the needed number of elements from the array, incrementing the '$offset' by the required count each time until the array was exhausted.

And as to your second question, try:

$num_ones=count(preg_grep(/^1$/,$array));

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359956

I want split it up into individual arrays so that each array contains seven or less values.

Use array_chunk(), which is made expressly for this purpose.

Also how would you count the number of times 1 occurs in array one?

Use array_count_values().

$one = array(1,0,0,0,1,1,1);
$one_counts = array_count_values($one);
print_r($one_counts);

// prints
Array
(
    [0] => 3
    [1] => 4
)

Upvotes: 3

mario
mario

Reputation: 145482

array_chunk() is what you are looking for.

 $splitted = array_chunk($array, 7);

For counting the occurences I would be lazy. If your arrays only contain 1s or 0s, then a simple array_sum() would do:

 print array_sum($splitted[0]);    // for the first chunk

Upvotes: 5

Related Questions