Foreach 3 entries total sum of 12

Hi there,
I’m working with a 12 column grid and I’m trying to create some restrains on the random generated width of each column. Currently I’m having the code generate a min width of 2 columns and max of 5 for each $item.

<?php foreach($page->children()->flip()->visible() as $item): ?>

<?php $random_size = rand(2,5); ?>

<div class="cell small-12 medium-<?php echo $random_size; ?>" >
// stuff here
</div>

<?php endforeach ?>

What would be the way to assign random width, but the sum of each 3 to be 12.
The result to be something like:

2 - 5 - 5
5 - 3 - 4
2 - 8 - 2
etc…
…and for last one/two (if there are no 3 left) anything between 2 and 5

Something like this:

$a = rand(2,5);
$b = rand(2,5);
$c = 12 - $a + $b;

?

Little correction:

$c = 12 - $a - $b; 

Code suggestion (don’t know if there’s a better way)

<?php
$projects = $page->children()->visible();
$randomArray = [];

foreach($projects as $item):
  
$index = $projects->indexOf($item);

  if($index%3 != 2) {
    $size = rand(2,5);
  } else {
    $size = 12-$randomArray[$index-1]-$randomArray[$index-2];
  }
  $randomArray[$index] = $size;

  $randomSize = $randomArray[$index];


?>
    <div class="cell small-12 medium-<?php echo $randomSize; ?>" >
     <!-- your code -->
    </div>

<?php endforeach ?>
1 Like